Vue3.0 基础
概述
Vue2.0的局限性:
- 当组件变得庞大复杂起来后,代码可阅读性降低
- 代码复用有明显的缺陷
TypeScript支持非常有限
版本对比
vue2和 vue3区别
vue3基于 vue2按需加载组件加快项目加载速度,原理是通过把 vue 库里的方法独立封装一个一个的函数,当组件需要使用时单独加载工具函数即可
createApp
调用 createApp 返回一个应用实例。该实例提供了一个应用上下文。应用实例挂载的整个组件树共享相同的上下文,该上下文提供了之前在 Vue 2.x 中“全局”的配置。
由于 createApp 方法返回应用实例本身,因此可以在其后链式调用其它方法
/*** {* component: ƒ component(name, component),* config: Object,* directive: ƒ directive(name, directive),* mixin: ƒ mixin(mixin),* mount: (containerOrSelector) => {…},* provide: ƒ provide(key, value),* unmount: ƒ unmount(),* use: ƒ use(plugin, ...options),* version: "3.2.23",* _component: {},* _container: null,* _context: {app: {…}, config: {…}, mixins: Array(0), components: {…},* directives: {…}, …},* _instance: null,* _props: null,* _uid: 0,* get config: ƒ config(),* set config: ƒ config(v)* }*/
component
//如果传入 参数,返回应用实例。const app = createApp({});const comp = app.component('my-component', {name: 'MyComponet',setup() {}})//返回的是应用实例console.log(comp);
mount
挂载应用实例的根组件
//返回根组件实例const app = createApp({})const rootIns = app.mount('#app')console.log(rootIns);//Proxy{...}
unmont
卸载应用实例的根组件
const app = createApp({})app.mount('#app')// 挂载5秒后,应用将被卸载setTimeout(() => app.unmount(), 5000)
use
安装 Vue.js 插件。如果插件是一个对象,它必须暴露一个 install 方法。如果它本身是一个函数,它将被视为安装方法。
该安装方法将以应用实例作为第一个参数被调用。传给 use 的其他 options 参数将作为后续参数传入该安装方法。
当在同一个插件上多次调用此方法时,该插件将仅安装一次。
import { createApp } from 'vue'import MyPlugin from './plugins/MyPlugin'const app = createApp({})app.use(MyPlugin)app.mount('#app')
config
包含应用配置的对象, 在挂载应用之前,你可以修改其 属性
config.errorHandler
app.config.errorHandler = (err, vm, info) => {// 处理错误// `info` 是 Vue 特定的错误信息,比如错误所在的生命周期钩子}
指定一个处理函数,来处理组件渲染方法和侦听器执行期间抛出的未捕获错误。这个处理函数被调用时,可获取错误信息和应用实例。
globalProperties
添加一个可以在应用的任何组件实例中访问的全局 property。组件的 property在命名冲突具有优先权
这可以代替 Vue 2.x里 Vue.prototype 扩展:
// 之前(Vue 2.x)Vue.prototype.$http = () => {}// 之后(Vue 3.x)const app = createApp({})app.config.globalProperties.$http = () => {}//使用const { ctx } = getCurrentInstance();console.log(ctx.utils.plus(1, 2));
组合 API
hooks是 vue3底层提供的钩子实现函数方式(不像 vue2 options API),开发者只需写提供钩子里面的逻辑
基于函数抽离的组合各种方法函数实现高内聚的情况(2.0 有横向拆分,各个组件都有如 data,method,computed)
CompositionAPI
解决问题是vue 2.0中当组件变得庞大复杂起来后,代码可阅读性降低
问题:什么时候使用CompositionAPI?
- 希望有最理想的
TypeScript支持 - 当组件的内容变得庞大复杂起来的时候,并且希望通过功能来管理组件
- 可能会有一些想要在不同的组件里使用的代码(代码复用)
- 团队倾向新的
CompositionAPI
//vue2.0写法:export default {data() {return {search,sorting}},methods: {search,sorting},props: {search,sorting}}
//vue3.0写法:(可选/不影响2.0使用)export default {setup() {//Composition API语法search,sorting}}
export default {setup() {//Composition functionsreturn {...useSearch(),...useSorting()}}}//搜索function useSearch() {}//排序function useSorting() {}
vue2.0代码复用的三种方式:
mixin提取公共代码到数组管理Mixin Factories工厂Scoped Slots作用域插槽方式
//方式一:mixins//存在优点://1.根据不同的功能进行归类//存在缺点://1.容易产生重复定义冲突//2.复用性不高const productSearchMixin = {data() {search},methods: {search}}const resultSortMixin = {data() {sorting},methods: {sorting}}export default {mixins: [productSearchMixin, resultSortMixin]}
//方式二:Mixin Factories//存在优点://1.提高可复用性//存在缺点://1.命名空间需要有严格的规范//2.暴露的属性需要进入到Mixin工厂函数的定义文件里查看//3.Factories不能动态生成//组件部分:import searchMixinFactory from '@mixins/factories/search';import sortingMixinFactory from '@mixins/factories/sorting';export default {mixins: [searchMixinFactory({namespace: 'productSearch',xxx}),sortingMixinFactory({namespace: 'productSorting',xxx}),]}//逻辑部分:export default function sortingMixinFactory(obj) { }
//方式三:Scoped Slots//存在优点://1.解决Mixins大多数问题//存在缺点://1.配置需要模板完成,理想的状态模板只定义需要渲染的内容//2.缩进降低代码的可阅读性//3.暴露的属性只能够在模板里使用//4.3个组件比1个组件,性能开销上升//generic-search.vue组件部分:<script>export default {props:['getResults']}</script><template><div><slot v-bind="{query, results, run}"></slot></div></template>//generic-sorting.vue组件部分:<script>export default {props:['input', 'options']}</script><template><div><slot v-bind="{options, index, output}"></slot></div></template>//search.vue组件部分:<template><div><generic-search:get-results="getProducts":v-slot="productSearch"><generic-sorting:input="productSearch.results":options="resultSortingOptions"v-slot="resultSorting"></generic-sorting></generic-search></div></template><script>export default {}</script>
问题:如何使用CompositionAPI?
//安装npm i -S @vue/composition-api//引用import VueCompositionApi from '@vue/composition-api';//注册Vue.use(VueCompositionApi);
setup
一个组件选项,在组件被创建之前,props 被解析之后执行。
它是组合式 API的入口。
setup返回一个对象,对象里的属性将被合并到render函数执行期上下文里,所以视图模板可以使用对象里的数据
当视图模板访问对象属性时,不需要.value写法
setup方法必须返回 view模板里定义的数据和方法
export default {setup(props, context){//必须返回视图模板需要的属性和方法return {}},}
setup函数在以下之前执行:
Components/props/data/methods/computed/lifecycle
setup写法:
import { watch } from 'vue';export default {setup(props, context){//监听props里面的属性watch(()=>{console.log(props.name);});//因为不能访问this,但通过context可访问://context.attrs/slots/parent/root/listeners},props:{name: String}}
参数
- 接收的第一个参数为:被解析后的
props - 接收的第二个参数为:执行期上下文
setup(props){}
注意: 接收的
props已经被响应式代理了对象, 且不要解构props否则失去响应式
console.log(props);//Proxy{...}
console.log(ctx);/*** {* attrs: (...),* emit: (...), 这里emit代替vue2 this.$emit* expose: exposed => {…},* slots: (...),* get attrs: ƒ attrs(),* get slots: ƒ slots()* }*/
参数 2 可以解构使用:
setup(props, {attrs, emit, slots}){...}
setup(props, ctx){const { attrs, emit, slots } = ctx;}
在子组件里的setup想要拿到vuex.$store属性和方法时,
//getCurrentInstance:拿状态和方法通过 获取当前实例 的函数方法//computed函数 计算和保存拿到的状态和方法import { getCurrentInstance, computed } from 'vue';export default {name: 'xxx',props: {index: Number},setup(props){//ctx -> store -> state/mutaionsconst { ctx } = getCurrentInstance(),store = ctx.$store;const changeCityInfo = () => {//提交给mutations里的方法去操作数据store.commit('changeCity', props.index);};//返回视图模板需要的数据和方法return {//拿到state里的数据curIdx: computed(() => store.state.curIdx),changeCityInfo}}}
ref
接受一个内部值并返回一个响应式且可变的 ref对象。ref对象仅有一个 .value property,指向该内部值。
/*** RefImpl{* dep: undefined,* __v_isRef: true,* _rawValue: "张三",* _shallow: false,* _value: "张三",* value: (...)* }*/
const count = ref(0)console.log(count.value) // 0
如果将对象分配为 ref值,则它将被 reactive函数处理为深层的响应式对象。
const obj = ref({a: 1,b: 2});/*** RefImpl{* ...,* value: Proxy{...}* }*///value会做reactive响应式处理
reactive 将解包所有深层的refs同时维持 ref的响应性。
const count = ref(1)const obj = reactive({ count })// ref 会被解包console.log(obj.count === count.value) // true// 它会更新 `obj.count`count.value++console.log(count.value) // 2console.log(obj.count) // 2// 它也会更新 `count` refobj.count++console.log(obj.count) // 3console.log(count.value) // 3
当将 ref 分配给 reactive property 时,ref 将被自动解包。const count = ref(1);const obj = reactive({});console.log(obj.count === count.value); // falseobj.count = count;console.log(obj.count); // 1console.log(obj.count === count.value); // true
Reactive References / refs
响应式引用值作用:
选择性暴露响应式对象数据有利于后期代码维护,也能更好的追踪到模板里的属性定义的位置
ref()
<div>容量:{{ capacity }}</div>import { ref } from '@vue/composition-api';export default {setup(){//传入原始值并执行会创建ref对象//ref() => ref对象 => 响应式属性const capacity = ref(3);console.log(capacity);/*** RefImpl:* {* value: 3,* get value(){}* set value(){}* }*///必须返回对象才能供模板表达式使用//不返回会报错:模板使用了但未定义return { capacity };}}
方法定义:
<div>容量:{{ capacity }}</div><button @click="increaseCapacity()">增加容量</button>import { ref } from '@vue/composition-api';export default {setup(){const capacity = ref(3);function increaseCapacity(){capacity.value ++;};return { capacity, increaseCapacity };}}
计算方法:
<p>座位容量:{{ capacity }}</p><p>剩余座位容量:{{spacesLeft}}/{{capcity}}</p><button @click="increaseCapacity()">增加容量</button><h2>参加人员</h2><ul><li v-for="(name, index) in attending" :key="index">{{name}}</li></ul>//引入computed计算函数import { ref, computed } from '@vue/composition-api';export default {setup(){const capacity = ref(3);const attending = ref(['小王', '小李', '小张']);//定义计算函数方法const spacesLeft = computed(()=>{return capacity.value - attending.value.length;});function increaseCapacity(){capacity.value ++;};//导出spacesLeft计算属性方法return {capacity,attending,spacesLeft,increaseCapacity};}}
模板引用:
在使用组合式 API时,响应式引用和模板引用的概念是统一的。为了获得对模板内元素或组件实例的引用,我们可以像往常一样声明 ref并从setup返回:
//1.在dom上使用可以拿到dom元素//2.在组件上使用可以拿到组件实例,可以访问实例里的属性和方法<div><div ref="child">张三</div><button @click="changeName">改变名字</button></div>setup(props, ctx) {//引用模板的固定写法:const child = ref(null);const changeName = () => {// console.log(child.value);//<div>张三</div>//修改页面上的文本为child.value.innerText = "李四";};return {child,changeName,};}
这里我们在渲染上下文中暴露 root,并通过 ref="child",将其绑定到 div作为其 ref。
在虚拟 DOM补丁算法中,如果 VNode的 ref 键对应于渲染上下文中的 ref,则 VNode的相应元素或组件实例将被分配给该 ref的值。这是在虚拟 DOM挂载/打补丁过程中执行的,因此模板引用只会在初始渲染之后获得赋值。
作为模板使用的 ref的行为与任何其他 ref一样:它们是响应式的,可以传递到 (或从中返回) 复合函数中。
v-for中的用法:组合式 API模板引用在 v-for 内部使用时没有特殊处理。相反,请使用函数引用执行自定义处理:
<template>//将divs每一项赋值给el<li v-for="(item, i) in list" :ref="el => { if (el) divs[i] = el }">{{ item }}</li></template><script>import { ref, reactive, onBeforeUpdate } from 'vue'export default {setup() {const list = reactive([1, 2, 3])const divs = ref([])// 确保在每次更新之前重置refonBeforeUpdate(() => {console.log(divs.value);//Proxy{0: li, 1: li, 2: li}console.log(divs.value[0]);//<li>...<li>})return {list,divs}}}</script>
unref
如果参数是一个ref, 则返回内部值,否则返回参数本身。这是 val = isRef(val) ? val.value : val 的语法糖函数。
toRef
可以用来为源响应式对象上的某个 property新创建一个ref ,更多的针对响应式数据
然后,ref可以被传递,它会保持对其源 property的响应式连接。
const state = reactive({foo: 1,bar: 2})const fooRef = toRef(state, 'foo')//state.foo和fooRef.value相互关联,哪个修改都会同步修改fooRef.value++console.log(state.foo) // 2state.foo++console.log(fooRef.value) // 3
当你要将 prop的 ref传递给复合函数时,toRef 很有用:
//可以自定义composition APIfunction useDoSth(name) {return `My name is ${name.value}.`;}export default {setup(props) {const state = reactive({name: "张三",age: 30,});const sentence = useDoSth(toRef(state, "name"));console.log(sentence);//My name is 张三.}}
toRefs
将响应式对象转换为普通对象,其中结果对象的每个 property都是指向原始对象相应 property的 ref
const state = reactive({foo: 1,bar: 2})const stateAsRefs = toRefs(state);// ref 和原始 property 已经“链接”起来了state.foo++console.log(stateAsRefs.foo.value) // 2stateAsRefs.foo.value++console.log(state.foo) // 3
const state = reactive({name: "张三",age: 30,});const stateRefs = toRefs(state);// console.log({ ...stateRefs });//{name: ObjectRefImpl, age: ObjectRefImpl}// console.log(stateRefs.name);//ObjectRefImpl {...}// console.log(stateRefs.name.value);//张三
当从组合式函数返回响应式对象时,toRefs 非常有用,这样消费组件就可以在不丢失响应性的情况下对返回的对象进行解构/展开:
const { name, age } = { ...toRefs(state) };console.log(name);console.log(age);
问题:Vue3为什么要使用toRefs?
reactive函数可以将ref定义的属性归并在一起,在模板绑定使用时写法是
<li>姓名:{{reactive函数执行返回的变量名.属性名}}</li>
可以看出在模板里使用时用xxx.属性名的写法比较麻烦,那么如何直接用属性名的写法呢?
可以通过toRefs函数实现, 它可以将多个ref定义的响应式属性/reactive响应式对象通过展开运算符的方式一并return到视图使用
import { reactive, toRefs } from 'vue';setup(){const person = reactive({name: 'lisi',age: 29});return {...toRefs(person);}}//视图写法:<li>{{name}}</li>
reactive
返回对象的响应式副本, 是“深层”影响所有嵌套 property。
有一个事件触发或一个视图上或数据上的改变,相对于被绑定方的数据也一起被改变
const state = reactive({count: 0});
reactive()
该函数返回的是真正的响应式对象
//reactive()写法:<p>座位容量:{{ event.capacity }}</p><p>剩余座位容量:{{event.spacesLeft}}/{{event.capcity}}</p><button @click="increaseCapacity()">增加容量</button><h2>参加人员</h2><ul><li v-for="(name, index) in event.attending" :key="index">{{name}}</li></ul>//写法二:toRefs()简写<p>座位容量:{{ capacity }}</p><p>剩余座位容量:{{spacesLeft}}/{{capcity}}</p><button @click="increaseCapacity()">增加容量</button><h2>参加人员</h2><ul><li v-for="(name, index) in attending" :key="index">{{name}}</li></ul>//引入computed计算函数import { reactive, computed, toRefs } from '@vue/composition-api';export default {setup(){//reactive()接收一个对象作为参数const event = reactive({capacity: 4,attending: ['小王', '小李', '小张'],spacesLeft: computed(()=>{return event.capacity - event.attending.length;});});function increaseCapacity(){return event.capacity ++;}return { event, increaseCapacity };//写法二://toRefs()将响应式对象转换为普通对象//...平铺开对象//既可以保持属性响应式,又能进行简写响应式对象平铺//return { ...toRefs(event), increaseCapacity };//写法三://因为toRefs()方法返回的是一个响应式对象//所以可以直接返回该对象//return toRefs();}}
readonly
接受一个对象 (响应式或纯对象) 或 ref 并返回原始对象的只读代理。只读代理是深层的:任何被访问的嵌套 property 也是只读的。
Composition Functions
提取代码,做代码复用的解决方案
解决问题:代码复用有明显的缺陷
//优点://1. 代码量减少,能够更容易地把功能从组件内部提取到一个函数里//2. 因为使用的是函数,使用的是现有的知识//3. 更灵活,技能感知,自动补全等编辑器里提示的功能利于编写代码//缺点://1.学习low-level API知识来定义Composition Functions//2. 3.0定义组件的方式变成了2种//写法://其他组件使用:import useEventSpace from '@/use/event-space';export default {setup(props, context){//执行函数并返回对象return useEventSpace();}}//定义在组件 src/use/event-space.js//Composition Function<script>import { ref, computed } from '@vue/composition-api';export default function useEventSpace(){const capacity = ref(3);const attending = ref(['小王', '小李', '小张']);spacesLeft: computed(()=>{return event.capacity - event.attending.length;});function increaseCapacity(){capacity.value++;}return {capacity,attending,spacesLeft,increaseCapacity}}</script>
生命周期

选项式 API的生命周期选项和组合式 API之间的映射
beforeCreate-> 使用setup():- 在实例初始化之后、进行数据侦听和事件/侦听器的配置之前同步调用
created-> 使用setup():- 在实例创建完成后被立即同步调用。在这一步中,实例已完成对选项的处理,意味着以下内容已被配置完毕:数据侦听、计算属性、方法、事件/侦听器的回调函数。然而,挂载阶段还没开始,且
$elproperty 目前尚不可用。
- 在实例创建完成后被立即同步调用。在这一步中,实例已完成对选项的处理,意味着以下内容已被配置完毕:数据侦听、计算属性、方法、事件/侦听器的回调函数。然而,挂载阶段还没开始,且
beforeMount->onBeforeMount:- 在挂载开始之前被调用:相关的
render函数首次被调用。
- 在挂载开始之前被调用:相关的
mounted->onMounted:- 在实例挂载完成后被调用,这时候传递给
app.mount的元素已经被新创建的vm.$el替换了。如果根实例被挂载到了一个文档内的元素上,当mounted被调用时,vm.$el也会在文档内。 注意mounted不会保证所有的子组件也都被挂载完成。如果你希望等待整个视图都渲染完毕,可以在mounted内部使用vm.$nextTick
- 在实例挂载完成后被调用,这时候传递给
beforeUpdate->onBeforeUpdate:- 在数据发生改变后,
DOM被更新之前被调用。这里适合在现有DOM将要被更新之前访问它,比如移除手动添加的事件监听器。
- 在数据发生改变后,
updated->onUpdated:- 在数据更改导致的虚拟
DOM重新渲染和更新完毕之后被调用。当这个钩子被调用时,组件DOM已经更新,所以你现在可以执行依赖于DOM的操作。然而在大多数情况下,你应该避免在此期间更改状态。如果要相应状态改变,通常最好使用计算属性或侦听器取而代之。注意,updated不会保证所有的子组件也都被重新渲染完毕。如果你希望等待整个视图都渲染完毕,可以在updated内部使用vm.$nextTick
- 在数据更改导致的虚拟
beforeUnmount->onBeforeUnmount:- 在卸载组件实例之前调用。在这个阶段,实例仍然是完全正常的
unmounted->onUnmounted:- 卸载组件实例后调用。调用此钩子时,组件实例的所有指令都被解除绑定,所有事件侦听器都被移除,所有子组件实例被卸载
errorCaptured->onErrorCaptured:- 在捕获一个来自后代组件的错误时被调用。此钩子会收到三个参数:错误对象、发生错误的组件实例以及一个包含错误来源信息的字符串。此钩子可以返回
false以阻止该错误继续向上传播
- 在捕获一个来自后代组件的错误时被调用。此钩子会收到三个参数:错误对象、发生错误的组件实例以及一个包含错误来源信息的字符串。此钩子可以返回
renderTracked->onRenderTracked:- 跟踪虚拟
DOM重新渲染时调用。钩子接收debugger event作为参数。此事件告诉你哪个操作跟踪了组件以及该操作的目标对象和键
- 跟踪虚拟
renderTriggered->onRenderTriggered:- 当虚拟
DOM重新渲染被触发时调用。和renderTracked类似,接收debugger event作为参数。此事件告诉你是什么操作触发了重新渲染,以及该操作的目标对象和键
- 当虚拟
activated->onActivated:- 被
keep-alive缓存的组件激活时调用
- 被
deactivated->onDeactivated:- 被
keep-alive缓存的组件失活时调用。
- 被
//vue3.0改动//为什么进行改动?//因为语义化挂载的反义词也有beforeDestyory -> beforeUnmountdestroyed -> unmounted
//钩子使用import { onBeforeMount } from '@vue/composition-api';export default {setup(){onBeforeMount(()=>{console.log('Before Mount!');})}}
新增生命钩子函数有:
onActivated/onDeactivated/onErrorCaptured/onRenderTracked/onRenderTriggered 追踪响应式依赖
computed
接受一个 getter函数,并根据 getter的返回值返回一个不可变的响应式 ref对象
const count = ref(1);const plusOne = computed(() => count.value + 1);console.log(plusOne.value); // 2plusOne.value++;// 错误 Write operation failed: computed value is readonly
或者,接受一个具有 get 和 set 函数的对象,用来创建可写的 ref对象
const count = ref(1)const plusOne = computed({get: () => count.value + 1,set: val => {count.value = val - 1}})plusOne.value = 1console.log(count.value) // 0
问题:为什么在setup返回时需要computed重新计算?
export default {...,setup() {return {//注意:在vue2.x中是通过computed里 ...mapState(['xxx'])方法拿到里面的属性//1.所以这里不能直接访问state.headerTitle//2.所以需要用computed函数取出state里的属性headerTitle: computed(() => state.headerTitle),};},};
侦听器
//侦听器写法:<div><input type="text"/><div>符合关键字的活动的数目: {{results}}</div></div>import { ref, watch } from '@vue/composition-api';import eventApi from '@/api/event.js';export default {setup(){const searchInput = ref('');const results = ref(0);//侦听searchInput属性,若发生变化执行右侧的箭头函数watch(searchInput, (newValue, oldValue)=>{results.value = eventApi.getEventCount(searchInput.value);});//多属性数据写法watch([firstName, lastName], ([newFirst, newLast], [oldFirst, oldLast])=>{results.value = eventApi.getEventCount(searchInput.value);});//setup函数底下的getEventCount()方法只触发一次//不能实时监听,所以用watch侦听//results.value = eventApi.getEventCount(searchInput.value);return{ searchInput, results };}}
watch
watch 的API完全等同于组件侦听器 property。watch 需要侦听特定的数据源,并在回调函数中执行副作用。默认情况下,它也是惰性的,即只有当被侦听的源发生变化时才执行回调。
与 watchEffect 比较,
watch允许我们:- 懒执行副作用;
- 更具体地说明什么状态应该触发侦听器重新运行;
- 访问侦听状态变化前后的值。
侦听单个数据源
侦听器数据源可以是返回值的 getter函数,也可以直接是 ref:
// 侦听一个 getterconst state = reactive({ count: 0 })watch(() => state.count,(count, prevCount) => {/* ... */})// 直接侦听refconst count = ref(0)watch(count, (count, prevCount) => {/* ... */})
侦听多个数据源
侦听器还可以使用数组同时侦听多个源:
const firstName = ref('')const lastName = ref('')watch([firstName, lastName], (newValues, prevValues) => {console.log(newValues, prevValues)})firstName.value = 'John' // logs: ["John", ""] ["", ""]lastName.value = 'Smith' // logs: ["John", "Smith"] ["John", ""]
尽管如此,如果你在同一个函数里同时改变这些被侦听的来源,侦听器仍只会执行一次:
setup() {const firstName = ref('')const lastName = ref('')watch([firstName, lastName], (newValues, prevValues) => {console.log(newValues, prevValues)})const changeValues = () => {firstName.value = 'John'lastName.value = 'Smith'// 打印 ["John", "Smith"] ["", ""]}return { changeValues }}
通过 watch Componsition API 实现数据监听
//当数据变化时import { watch } from "vue";export default {setup(){watch(()=>{return xxx;},(value)=>{//业务需求:操作state里的数据,调用mutatios里面的方法store.commit("setHeaderTitle", value);});//这里的value是前面第一个函数里return的值}};
watchEffect
立即执行传入的一个函数,同时响应式追踪其依赖,并在其依赖(数据)变更时重新运行该函数。
const count = ref(0);watchEffect(() => {console.log(count.value);//0 首次立即执行});setTimeout(() => {count.value = 1;//再次执行watchEffect并打印 1}, 100);
停止侦听
当 watchEffect 在组件的setup函数或生命周期钩子被调用时,侦听器会被链接到该组件的生命周期,并在组件卸载时自动停止。
在一些情况下,也可以显式调用返回值以停止侦听:
const stop = watchEffect(() => {/* ... */})// laterstop()
清除副作用
有时副作用函数会执行一些异步的副作用,这些响应需要在其失效时清除 (即完成之前状态已改变了) 。所以侦听副作用传入的函数可以接收一个 onInvalidate 函数作入参,用来注册清理失效时的回调。当以下情况发生时,这个失效回调会被触发:
- 副作用即将重新执行时
- 侦听器被停止 (如果在
setup()或生命周期钩子函数中使用了watchEffect,则在组件卸载时)
watchEffect(onInvalidate => {const token = performAsyncOperation(id.value)onInvalidate(() => {// id has changed or watcher is stopped.// invalidate previously pending async operationtoken.cancel()})})
我们之所以是通过传入一个函数去注册失效回调,而不是从回调返回它,是因为返回值对于异步错误处理很重要。
在执行数据请求时,副作用函数往往是一个异步函数:
const data = ref(null)watchEffect(async onInvalidate => {onInvalidate(() => {/* ... */}) // 我们在Promise解析之前注册清除函数data.value = await fetchData(props.id)})
provide/inject
使用一对 provide 和 inject。无论组件层次结构有多深,父组件都可以作为其所有子组件的依赖提供者。这个特性有两个部分:父组件有一个 provide 选项来提供数据,子组件有一个 inject 选项来开始使用这些数据。
在此处 provide一些组件的实例 property,这将是不起作用的:
app.component('todo-list', {...,provide: {todoLength: this.todos.length// 将会导致错误 `Cannot read property 'length' of undefined`},})
要访问组件实例 property,我们需要将 provide 转换为返回对象的函数:
app.component('todo-list', {...,provide() {return {todoLength: this.todos.length}}})
响应式处理
默认情况下,provide/inject 绑定并不是响应式的。我们可以通过传递一个 ref property或 reactive 对象给 provide 来改变这种行为
app.component('todo-list', {// ...provide() {return {todoLength: Vue.computed(() => this.todos.length)}}})app.component('todo-list-statistics', {inject: ['todoLength'],created() {console.log(`Injected property: ${this.todoLength.value}`)// > 注入的 property: 5}})
setup写法
//provideexport default {setup() {provide('location', 'North Pole')provide('geolocation', {longitude: 90,latitude: 135})}}
//injectexport default {setup() {const userLocation = inject('location', 'The Universe')const userGeolocation = inject('geolocation')return {userLocation,userGeolocation}}}
响应式处理
//添加响应性export default {setup() {const location = ref('North Pole')const geolocation = reactive({longitude: 90,latitude: 135})provide('location', location)provide('geolocation', geolocation)}}
