简述Vue2.x中computed相互调用,以及watch中同一属性多次监听 您所在的位置:网站首页 忆昔如梦图片大全 简述Vue2.x中computed相互调用,以及watch中同一属性多次监听

简述Vue2.x中computed相互调用,以及watch中同一属性多次监听

2024-07-17 10:20| 来源: 网络整理| 查看: 265

平时在开发的时候,在需要做数据计算的时候,会用computed计算属性,但是在computed中的某一属性是否可以调用另一属性呢?在应用侦听属性watch的时候,如何对同一属性进行多次侦听呢?

computed相互调用

通过上一篇文章的分析,可以了解到computed其中的内部实现原理,即:

在初始化的时候,创建订阅者Dep,并应用Object.defineProperty对computed中计算属性进行转换拦截,定义的方法作为该属性的get方法,同时在方法内部创建观察者computedWatcher。当被render方法调用的时候,订阅renderWatcher,放入自身的Dep中,而在computed中调用的其它数据,也会执行一样的操作。

从这就可以看出,computed的实现原理与data数据基本类似,都是应用了响应式原理的三个主要特性,Object.defineProperty、Dep、Watcher,所以在computed中也是可以相互调用的,就像调用data数据一样,其内部实现原理也是同样执行上面说的。

举例说明一下:

12345678910111213141516171819202122232425262728293031 {{ message }} {{ newMessage1 }} {{ newMessage2 }} change export default { data(){ return { message: 'hello' } }, computed: { newMessage1(){ return this.message + ' world' }, newMessage2(){ return this.newMessage1 + '!' } }, method: { changeMessage(){ this.message = 'hi' } } }

首次渲染的时候,页面上的显示分别为hello、hello world、hello world!,当点击按钮后,页面上的显示会变为hi,hi world,hi world!

watch中同一属性多次监听

正常开发时,当某一属性发生变化时,要执行某操作会用到watch,如果想执行多种操作的时候,该怎么办呢?其实看一下Vue的源码就能轻松知道。

先贴一下Vue的相关源码:

12345678910111213141516171819202122232425262728function initWatch (vm: Component, watch: Object) { for (const key in watch) { const handler = watch[key] if (Array.isArray(handler)) { for (let i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]) } } else { createWatcher(vm, key, handler) } }}function createWatcher ( vm: Component, expOrFn: string | Function, handler: any, options?: Object) { if (isPlainObject(handler)) { options = handler handler = handler.handler } if (typeof handler === 'string') { handler = vm[handler] } return vm.$watch(expOrFn, handler, options)}

从上面的源码中可以看出,在定义watch的时候,不止能定义单一的侦听函数,还能定义数组,数组中的每个元素可以为对象,在对象内定义要执行的侦听函数。

还是举例说明一下:

1234567891011121314151617181920212223242526272829303132333435 {{ message }} change export default { data(){ return { message: 'hello' } }, watch: { message: [ { handler(){ console.log('message is changed') } }, { handler(){ console.log('new message output') } } ] }, methods: { changeMessage(){ this.message = 'world' } } }

当点击按钮后,在控制台会输出message is changed,new message output。

这里要注意的是,在写数组中对象的时候,定义的方法的key值,必须为handler,这一点从源码中可以看出。当然在对象内部也可以定义deep等其它属性。如果只有一个对象的时候,也可以不用数组包围,直接定义,但同样的要用handler作为侦听函数的key值。

总结

平时在实际开发中,以上的操作可能应用不会很多。但是在通过阅读源码之后就能了解到其底层的实现原理,以及一些其它的定义方式,这样不管开发还是学习都能有不断的提升。

谢谢你请我吃糖果



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有