vue3尝鲜--使用Composition API做个todoList
程序员文章站
2022-03-03 10:04:17
...
vue3 RC版本已经出了,正式发布还会远吗(狗头)。 各位还学得动吗,哈哈~
关于vue3跟vue2的区别这里就不再多说,直接看代码最直接吧,今天使用vue3做一个简单的todoList来感受一下vue3
<template>
<div class="hello">
<input type="text" v-model="value" @keydown.enter="handleEnter">
<span>你按了{{count}}次回车, 双倍是{{doubleCount}}</span>
<ul>
<li v-for="(item, index) in todoList" :key="item">{{item}} <button @click="handleDelete(index)">删除</button></li>
</ul>
</div>
</template>
<script>
import { ref, reactive, toRefs, computed } from 'vue'
export default {
setup() {
// ref:接受一个参数值并返回一个响应式且可改变的 ref 对象。ref 对象拥有一个指向内部值的单一属性
const count = ref(0)
// 计算属性
const doubleCount = computed(() => count.value * 2)
// reactive:接收一个普通对象然后返回该普通对象的响应式代理。等同于 2.x 的 Vue.observable()
const state = reactive({
value: '',
todoList: ['a', 'b']
})
function handleEnter() {
state.todoList.push(state.value)
count.value++
}
function handleDelete(index) {
state.todoList.splice(index, 1)
}
// toRefs 把一个响应式对象转化为普通对象。
return { ...toRefs(state), count, doubleCount, handleEnter, handleDelete }
// 如果不使用toRefs,则在template中使用state里面的属性都需要加上state,如state.todoList,state.value
// return { state, count, doubleCount, handleEnter, handleDelete }
}
}
</script>
总结一下
- 首先是写法上,跟vue2是完全不一样的写法,api的使用方式也变了。所以还是有一定的学习成本的。
- 维护性更好,以前如果要在项目中加个功能,需要在data,method等地方都去改,现在只需要在setup里面。
- vue3是使用proxy来做响应式的,所以对浏览器的兼容性要求要变高了,IE没救了,哈哈,不过据尤大说可能会对ie使用单独的一个降级版本
- vue3对
typescript
支持很好,赶紧学起来吧~
上一篇: watch侦听器(监听数据改变)
下一篇: vue中的侦听器-监听的小demo