开始之前
目前Vue3.0处于beta2阶段,官方为体验新特性的小伙伴准备了vue-next-webpack-preview(一个webpack的运行环境), clone下仓库按README运行即可。
初印象
src/main.js
创建实例由2.x的new改为createApp 。
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
src/App.vue
首先,template最外层可以由多个节点组成了。
<template>
<img src="./logo.png">
<h1>Hello Vue 3!</h1>
<button @click="inc">Clicked {{ count }} times.</button>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
const inc = () => {
count.value++
}
return {
count,
inc
}
}
}
</script>
然后,组件的形式发生了变化,setup是CompositionApi的写法。CompositionApi提供了新的组织组件逻辑的方式,相比mxin在可读性上有了提升。同时也兼容2.x的写法。
export default {
data() {
return {
count: 0
}
},
methods: {
inc() {
this.count++;
}
}
}
尝试todo-list
效果图.png
需要实现input输入,enter创建列表条目清空input,点击条目删除。
<template>
<h1>TODO-LIST</h1>
<input
type="text"
v-model="txt"
@keydown.enter="enter" />
<ul>
<li
v-for="(item, index) in list"
:key="item"
@click="remove(index)">{{item}}</li>
</ul>
</template>
<script>
import { ref, reactive } from 'vue';
export default {
setup() {
const txt = ref('');
const list = reactive([]);
const enter = () => {
if (txt.value) {
list.push(txt.value);
txt.value = '';
}
};
const remove = index => {
list.splice(index, 1);
}
return {
txt,
list,
enter,
remove
}
}
}
</script>
ref和reactive是在从底层响应式处理暴露的方法,ref用于处理基础类型,reactive用于处理对象,两者都会返回有响应能力的Proxy。ref返回的为{value: 原值}结构,不过在template中自动展开value。setup方法返回对象属性可在template中引用。
重组
CompositionApi的写法使得对列表的操作可以更紧凑的抽象出来。而且在由多部分混合时,相比mixin的写法,读者可以清晰地看到视野外声明的变量的来源,不必在mixins数组中查找。
因此在3.0中mixin不建议使用。
let thingsList = () => {
const list = reactive([]);
return {
list,
push(item) {
list.push(item);
},
remove(index) {
list.splice(index, 1);
}
}
}
export default {
setup() {
const txt = ref('');
let {push, ...others} = thingsList();
const enter = () => {
if (txt.value) {
push(txt.value);
txt.value = '';
}
};
return {
txt,
enter,
...others
}
}
}