【vue】watch监听对象及对象属性
<h3>computed</h3>
<hr />
<p>是一个计算属性,类似于过滤器,对绑定到view的数据进行处理</p>
<h4>get的用法</h4>
<p>fullName不可在data里面定义,</p>
<pre><code>data(){
return {
firstName:'Foo',
lastName:'Bar'
}
},
computed:{
fullName:function(){
return this.firstName+' '+this.lastName
}
}</code></pre>
<h4>get与set</h4>
<pre><code>data(){
return {
firstName:'Foo',
lastName:'Bar'
}
},
computed:{
fullName:{
get(){
return this.firstName+' '+this.lastName
},
set(val){
console.log(val) //fullName
var names = val.split(' ')
console.log(names)
this.firstName = names[0];
this.lastName = names[1];
}
}
}</code></pre>
<h3>watch</h3>
<hr />
<h4>监听简单数据的类型</h4>
<pre><code>data(){
return{
'first':2
}
},
watch:{
first(){
console.log(this.first)
}
},</code></pre>
<h4>监听整个对象</h4>
<pre><code>export default {
data() {
return {
a: {
b: 1,
c: 2
}
}
},
watch() {
a: {
handler(newVal, oldVal) {
console.log('监听a整个对象的变化');
},
deep: true
}
}
}</code></pre>
<h4>监听对象的单个属性</h4>
<p>方法一:可以直接对用对象.属性的方法拿到属性</p>
<pre><code>export default {
data() {
return {
a: {
b: 1,
c: 2
}
}
},
watch() {
'a.b': function(newVal,oldVal){
console.log('监听对象a.b的属性变化')
}
}
}</code></pre>
<p>方法二:
watch如果想要监听对象的单个属性的变化,必须用computed作为中间件转化,因为computed可以取到对应的属性值</p>
<pre><code>export default {
data() {
return {
a: {
b: 1,
c: 2
}
}
},
computed:{
bChange(){
return this.a.b ;
}
},
watch() {
bChange(newVal,oldVal) //新的值,旧的值
console.log(b的数据改变了)
}
}
}</code></pre>
<p>总结:
3.1 computed特性
1.是计算值,
2.应用:就是简化tempalte里面{{}}计算和处理props或$emit的传值
3.具有缓存性,页面重新渲染值不变化,计算属性会立即返回之前的计算结果,而不必再次执行函数</p>
<p>3.2 watch特性
1.是观察的动作,
2.应用:监听props,$emit或本组件的值执行异步操作
3.无缓存性,页面重新渲染时值不变化也会执行</p>