vue 中的watch 和 computed

watch :

Watch属性可以监视 data 中指定数据的变化,一旦被监听的数据值发生了改变,就会立即触发watch对应的 function处理函数:

<template>
     <div> 
        <input type="text" v-model="firstname" /> +
         <input type="text" v-model="lastname" /> = 
        <input type="text" v-model="fullname" />
     </div> 
</template>
export default { 
    data(){ 
        return{ 
            firstname:"",
             lastname:"",
             fullname:"" 
      } 
},
 watch:{ 
        //newVal:最新数据;
        //oldVal:上一次数据 
        "firstname":function(newVal,oldVal){
                 this.fullname = newVal+"-"+this.lastname;
         }, 
        "lastname":function(newVal){ 
                this.fullname = this.firstname+"-"+newVal; 
        } 
    } 
};

使用watch属性监听路由地址:

入口js文件的vue实例上添加watch属性 监听$route.path,只要地址栏中的url发生了改变,就会被监听到

var vm = new Vue({ 
        el: "#app", 
        render: c => c(App4), 
        router:routerObj,
         watch: {
                 "$route.path": function(newVal, oldVal) { 
                        console.log(newVal + ' --- ' + oldVal);
                 } 
        } 
})

在 computed 中定义的属性,叫做计算属性,计算属性的本质是 一个方法,但是我们在使用 这些计算属性的 时候,是把它们的名称,直接当作属性来使用的;并不会把计算属性当作方法去调用.

计算属性computed定义的属性不需要在data中声明

计算属性指向的function内部,所用到的data中的任何数据发生了变化,就会立即触发function,重新计算 这个属性的值

export default { 
    data() { 
        return { 
            firstname: "",
             lastname: "“
         }; 
    }, 
    computed: { 
        fullname: function() { 
                return this.firstname + "-" + this.lastname; 
        }
     } 
};

1:计算属性的求值结 果,会被缓存起来, 方便下次直接使用,提 高运算效率
2: fullname在data中 不能定义
3: 只要firstname或者 lastnama发生了改变, funciton会立即触发执行。

猜你喜欢

转载自www.cnblogs.com/panghu123/p/11735947.html