VUE专题(四)谈一下对$watch 和生命周期mounted的理解

《VUE专题(四)谈一下对$watch 和生命周期mounted的理解》 vue

vue.js源码当中有个注释是这样说的:
A watcher parses an expression, collects dependencies,
and fires callback when the expression value changes.
意思大概就是说watcher用来观察一个数据,收集依赖, 当一个数据发生变化时执行一个回调函数
如果我们观察一个数据,那么只有在变化的时候才会执行代码。
那么watch怎么用呢?
watch 是一个对象,键是要观察的数据,值可以是对应的回调函数,也可以是方法名,或者包含选项的对象,在工作中,我一般是用回调,观察某个数据的变化。
<pre>
props: [‘myServices’,’myService’],
data () {
return {
sDesc: ”,
sType: ”,
myChildServices: this.myService,
properties: [properties],
actions: []
}
},
//watch 和mounted 都要用
watch: {
myService() {
this.myChildServices = this.myService;
this.assignS();
}
},
mounted () {
this.assignS();
},
</pre>
注意!!这点是我在vue中踩坑的点!!
坑在与我的数据渲染始终不对,就是丢数据。
解决办法就是watch 和mounted同时用来完成数据渲染。
首先父组件传了一个myService,虽然我在data中让myChildServices = this.myService,
我以为这样即使值变化也会赋给myChildServices,然并卵。。
其实如果不用myChildServices作为桥梁也不会踩这个坑,所以我建议使用props传过来的值就直接采用this.myService就行。
在watch中,观察myServices的变化。myServices变化就会执行里边的代码。
我们想只要一变化,我们就把值再重新赋值一次就好了
this.myChildServices = this.myService;
对,就是这个样子,在vue中,watch就负责观察数据变化,并用新值覆盖旧值。
观察我的mounted 在mounted和watch中我都调用了assignS方法,这也是我遇到的一个坑点。
我发现我的数据渲染总是不对的,最开始我是watch 发现不对,改为mounted,还是不对,最后两个都加上,提出公共代码放在methods中,完美解决!
<pre>
//抽出公共函数
assignS () {
console.log(‘打印myChildServices’);
console.log(this.myChildServices);
if (this.myChildServices.type) {
this.sType = this.myChildServices.type.split(‘:’)[3];
}
if (this.myChildServices.description) {
this.sDesc = this.myChildServices.description;
}
if (this.myChildServices.properties) {
this.properties = this.myChildServices.properties;
}
if (this.myChildServices.actions) {
this.actions = this.myChildServices.actions;
}
},
</pre>
这段代码目的是要完成数据渲染
可能我这里先谈一个mounted会比较好理解
mouted:是vue的生命周期,
Vue实例有一个完整的生命周期,也就是从开始创建、初始化数据、编译模板、挂载Dom、渲染→更新→渲染、卸载等一系列过程,我们称这是Vue的生命周期。通俗说就是Vue实例从创建到销毁的过程,就是生命周期。
我经常用的就是mounted ,所以这里只说mounted, ,mounted 是指挂载完成,DOM结构加载完毕,一般要是执行ajax操作就是在这里。
我觉得是因为我这是组件嵌套的原因,可能我想得到某个值的时候DOM结构还没有加载完,更别说传值了,
所以我这里自然要执行mounted
所以到这里我觉得mounted 和 watch 结合的还是蛮好的
组件和watch的东西还有很多,也都在vue中有着举足轻重的地位。
希望大家多多交流多多分享吧..
远离坑

《VUE专题(四)谈一下对$watch 和生命周期mounted的理解》 vue交流群

    原文作者:腿毛崩你一脸
    原文地址: https://www.jianshu.com/p/b95adde117f0
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞