前言
Vue3.0 发布几天了,生态都在不断加急完善。下面盘点一些3.0的新特性。

图片来源:宝石之国-钻石
1. 初始化项目
1 2 3 4 5 6 7 8
|
import Vue from 'vue' import VueCompositionApi from '@vue/composition-api' Vue.use(VueCompositionApi)
|
2. setup方法
setup是vue3.x中新的操作组件属性的方法,它是组件内部暴露出所有的属性和方法的统一API。
2.1 执行时机
setup的执行时机在:beforeCreate 之后 created之前
1 2 3 4 5 6 7 8 9
| setup(props, ctx) { console.log('setup') }, beforeCreate() { console.log('beforeCreate') }, created() { console.log('created') },
|
2.2 接受props数据
1 2
| <!-- 组件传值 --> <com-setup p1="传值给 com-setup"/>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| setup(props) { console.log(props) },
props: { p1: String }
|
2.3 context
setup 函数的第二个形参是一个上下文对象,这个上下文对象中包含了一些有用的属性,这些属性在 vue 2.x 中需要通过 this 才能访问到,在 vue 3.x 中,它们的访问方式如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| setup(props, ctx) { console.log(ctx) console.log(this) },
|
注意:在 setup() 函数中无法访问到 this
3. reactive
reactive函数接收一个普通函数,返回一个响应式的数据对象。
reactive函数等价于 vue 2.x 中的 Vue.observable() 函数,vue 3.x 中提供了 reactive() 函数,用来创建响应式的数据对象,基本代码示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <template> <div> <p>当前的 count 值为:{{count}}</p> <button @click="count += 1">+1</button> </div> </template> <script> import {reactive} from '@vue/composition-api' export default { setup(props, ctx) { const state = reactive({ count: 0 }) state.count += 1 console.log(state) return state } } </script>
|
4. ref
ref() 函数用来根据给定的值创建一个响应式的数据对象,ref() 函数调用的返回值是一个对象,这个对象上只包含一个 .value 属性:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <template> <div> <h3>02.ref.vue 文件</h3> <p>refCount:{{refCount}}</p> <button @click="refCount += 1">+1</button> </div> </template>
<script> import { ref } from '@vue/composition-api' export default { setup() { const refCount = ref(0) console.log(refCount.value) refCount.value++ console.log(refCount.value) return { refCount } } } </script>
|
4.1 在 reactive 对象中访问 ref 创建的响应式数据
当把 ref() 创建出来的响应式数据对象,挂载到 reactive() 上时,会自动把响应式数据对象展开为原始的值,不需通过 .value 就可以直接被访问,例如:
1 2 3 4 5 6 7 8 9 10 11
| setup() { const refCount = ref(0) const state = reactive({refCount}) console.log(state.refCount) state.refCount++ console.log(refCount) return { refCount } }
|
注意:新的 ref 会覆盖旧的 ref,示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| setup() { const c1 = ref(0); const state = reactive({ c1 });
const c2 = ref(9); state.c1 = c2; state.c1++;
console.log(state.c1); console.log(c2.value); console.log(c1.value); }
|
5. isRef
isRef() 用来判断某个值是否为 ref() 创建出来的对象;应用场景:当需要展开某个可能为 ref() 创建出来的值的时候,例如:
1 2 3 4 5 6
| import { ref, reactive, isRef } from "@vue/composition-api"; export default { setup() { const unwrapped = isRef(foo) ? foo.value : foo } };
|
6. toRefs
toRefs() 函数可以将 reactive() 创建出来的响应式对象,转换为普通的对象,只不过,这个对象上的每个属性节点,都是 ref() 类型的响应式数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <template> <div> <h3>03.toRefs.vue文件</h3> <p>{{ count }} - {{ name }}</p> <button @click="count += 1">+1</button> <button @click="add">+1</button> </div> </template>
<script> import { reactive, toRefs } from "@vue/composition-api"; export default { setup() { const state = reactive({ count: 0, name: "zs" }); const add = () => { state.count += 1; }; return { ...toRefs(state), add }; } }; </script>
|
7. computed计算属性
7.1 只读的计算属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <template> <div> <h3>04.computed.vue文件</h3> <p>refCount: {{refCount}}</p> <p>计算属性的值computedCount : {{computedCount}}</p> <button @click="refCount++">refCount + 1</button> <button @click="computedCount++">计算属性的值computedCount + 1</button> </div> </template>
<script> import { computed, ref } from '@vue/composition-api' export default { setup() { const refCount = ref(1) let computedCount = computed(() => refCount.value + 1) console.log(computedCount) return { refCount, computedCount } } }; </script>
|
7.2 可读可写的计算属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| <template> <div> <h3>04.computed.vue文件</h3> <p>refCount: {{refCount}}</p> <p>计算属性的值computedCount : {{computedCount}}</p> <button @click="refCount++">refCount + 1</button> </div> </template>
<script> import { computed, ref } from '@vue/composition-api' export default { setup() { const refCount = ref(1) let computedCount = computed({ get: () => refCount.value + 1, set: val => { refCount.value = refCount.value -5 } }) console.log(computedCount.value) computedCount.value = 10 console.log(computedCount.value) console.log(refCount.value) return { refCount, computedCount } } }; </script>
|
8. watch
watch() 函数用来监视某些数据项的变化,从而触发某些特定的操作,使用之前需要按需导入:
1
| import { watch } from '@vue/composition-api'
|
8.1 基本用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <template> <div> <h3>05.watch.vue文件</h3> <p>refCount: {{refCount}}</p> </div> </template>
<script> import { watch, ref } from '@vue/composition-api' export default { setup() { const refCount = ref(100) watch(() => console.log(refCount.value), { lazy: false}) setInterval(() => { refCount.value += 2 }, 5000) return { refCount } } }; </script>
|
8.2 监视数据源
监视 reactive 类型的数据源:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <template> <div> <h3>05.watch.vue文件</h3> <p>count: {{count}}</p> // 不是响应式数据 </div> </template>
<script> import { watch, ref, reactive } from '@vue/composition-api' export default { setup() { const state = reactive({count: 100}) watch( () => state.count, (newVal, oldVala) => { console.log(newVal, oldVala) }, { lazy: true } ) setInterval(() => { state.count += 2 }, 5000) return state } }; </script>
|
监视 ref 类型的数据源:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| export default { setup() { let count = ref(0); watch(count, (count, prevCount) => { console.log(count, prevCount) }) setInterval(() => { count.value += 2 }, 2000) console.log(count.value) return { count } } };
|
8.3 监听多个数据源
监视 reactive 类型的数据源:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| export default { setup() { const state = reactive({count: 100, name: 'houfei'}) watch( [() => state.count, () => state.name], ([newCount, newName], [oldCount, oldName]) => { console.log(newCount, oldCount) console.log(newName, oldName) }, { lazy: true} ) setTimeout(() => { state.count += 2 state.name = 'qweqweewq' }, 3000) return state } };
|
监视 ref 类型的数据源:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| export default { setup() { const count = ref(10) const name = ref('zs') watch( [count, name], ([newCount, newName], [oldCount, oldName]) => { console.log(newCount, oldCount) console.log(newName, oldName) }, { lazy: true} ) setInterval(() => { count.value += 2 }, 2000) console.log(count.value) return { count } } };
|
8.4 清除监视
在 setup() 函数内创建的 watch 监视,会在当前组件被销毁的时候自动停止。如果想要明确地停止某个监视,可以调用 watch() 函数的返回值即可,语法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <script>
const stop = watch(() => { })
stop() </script>
<template> <div> <p>count: {{ count }}</p> <button @click="stopWatch">停止监听</button> </div> </template>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import { watch, ref, reactive } from "@vue/composition-api"; export default { setup() { const count = ref(10) const name = ref('zs') const stop = watch( [count, name], ([newCount, newName], [oldCount, oldName]) => { console.log(newCount, oldCount) console.log(newName, oldName) }, { lazy: true} ) setInterval(() => { count.value += 2 name.value = 'houyue' }, 2000) const stopWatch = () => { console.log("停止监视,但是数据还在变化") stop() } console.log(count.value) return { stop, count, stopWatch } } };
|
8.5 在watch中清除无效的异步任务
有时候,当被 watch 监视的值发生变化时,或 watch 本身被 stop 之后,我们期望能够清除那些无效的异步任务,此时,watch 回调函数中提供了一个 cleanup registrator function 来执行清除的工作。这个清除函数会在如下情况下被调用:
watch 被重复执行了
watch 被强制 stop 了
Template 中的代码示例如下:
1 2 3 4 5 6 7
| <template> <div> <input type="text" v-model="keywords" /> <p>keywords:--- {{ keywords }}</p> </div> </template>
|
Script 中的代码示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import { watch, ref, reactive } from "@vue/composition-api";
export default { setup() { const keywords = ref("");
const asyncPrint = val => { return setTimeout(() => { console.log(val); }, 1000); };
watch( keywords, (keywords, prevKeywords, onCleanup) => { const timerId = asyncPrint(keywords); onCleanup(() => clearTimeout(timerId)); }, { lazy: true } );
return { keywords }; } };
|
9. provide & inject 组件传值
provide() 和 inject() 可以实现嵌套组件之间的数据传递。这两个函数只能在 setup() 函数中使用。父级组件中使用 provide() 函数向下传递数据;子级组件中使用 inject() 获取上层传递过来的数据。
9.1 共享普通数据
app.vue 根组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <template> <div id="app"> <h1>父组件</h1> <button @click="color = 'blue'">蓝色</button> <button @click="color = 'red'">红色</button> <button @click="color = 'yellow'">黄色</button> <son></son> <son></son> </div> </template>
<script> import { ref, provide } from '@vue/composition-api' import Son from './components/06.son.vue'
export default { name: 'app', components: { 'son': Son }, setup() { const color = ref('green') provide('themecolor', color) return { color } } } </script>
|
son.vue son 组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <template> <div> <h3 :style="{color: color}">son 组件</h3> <grandson></grandson> </div> </template>
<script> import { inject } from '@vue/composition-api' import Grandson from './07.grandson.vue' export default { components: { 'grandson': Grandson }, setup() { const color = inject('themecolor') return { color } } } </script>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| grandson.vue son 组件:
<template> <div> <h5 :style="{color: color}">grandson 组件</h5> </div> </template>
<script> import { inject } from '@vue/composition-api' export default { setup() { const color = inject('themecolor') return { color } } } </script>
|
9.2 共享ref响应式数据
app.vue 根组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <template> <div id="app"> <h1>父组件</h1> <son></son> </div> </template>
<script> import { provide } from '@vue/composition-api' import Son from './components/06.son.vue'
export default { name: 'app', components: { 'son': Son }, setup() { provide('themecolor', 'red') } } </script>
|
son.vue son 组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <template> <div> <h3 :style="{color: color}">son 组件</h3> <grandson></grandson> </div> </template>
<script> import { inject } from '@vue/composition-api' import Grandson from './07.grandson.vue' export default { components: { 'grandson': Grandson }, setup() { const color = inject('themecolor') return { color } } } </script>
|
grandson.vue son 组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <template> <div> <h5 :style="{color: color}">grandson 组件</h5> </div> </template>
<script> import { inject } from '@vue/composition-api' export default { setup() { const color = inject('themecolor') return { color } } } </script>
|
10. 节点的引用 template ref
10.1 dom的引用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <template> <div> <h3 ref="h3Ref">TemplateRefOne</h3> </div> </template>
<script> import { ref, onMounted } from '@vue/composition-api'
export default { setup() { const h3Ref = ref(null)
onMounted(() => { h3Ref.value.style.color = 'red' })
return { h3Ref } } } </script>
|
10.2 组件的引用
App父组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <template> <div id="app"> <h1>父组件</h1> <button @click="showComRef">展示子组件的值</button> <son ref="comRef"></son> </div> </template>
import Son from './components/06.son.vue'
export default { name: 'app', components: { 'son': Son }, setup() { const comRef = ref(null) const showComRef = () => { console.log(comRef) console.log('str1的值是' + comRef.value.str1) comRef.value.setStr1() } return { comRef, showComRef } } }
|
son.vue子组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <template> <div> <h3 :style="{color: color}">son 组件</h3> <p>{{str1}}</p> </div> </template>
<script> import { ref } from '@vue/composition-api' export default { setup() { const str1 = ref('这是一个子组件!!') const setStr1 = () => { str1.value = '被赋值了' } return { str1, setStr1 } } } </script>
|
11 nextTick
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <template> <div> <h3>09.nextTick 组件</h3> <p>学习 $nextTick</p> <button v-if="isShowInput === false" @click="showInput">展示文本框</button> <input type="text" v-else ref="ipt"> </div> </template>
<script> export default { data() { return { isShowInput: false } }, methods: { showInput() { this.isShowInput = !this.isShowInput this.$nextTick(() => { this.$refs.ipt.focus() }) } } } </script>
|
参考资料