//watch computed 和 methods 之间的对比
1.computed :属性的结果会被缓存,除非依赖的响应式属性变化才会重新计算,主要是当属性使用,
2.methods :方法表示一个具体的操作,主要书写业务逻辑 (写方法)
3.watch : 一个对象,键是需要观察的表达式,值是对应回调函数,主要用来监听某些特定数据的变化,从而进行某些具体的业务逻辑操作;可以看做是computed 和methods的结合体
例子:
code html
<div id="app">
<input type="text" v-model="input1" /> +
<input type="text" v-model="input2" /> =
<input type="text" v-model="input3" />
</div>
vue.js
//1.computed
new Vue({
el:"#app",
data:{
input1:'',
input2:'',
},
methods:{},
computed:{
//在computed 中,可以定义一些属性,这些属性叫做计算属性(本质是一个方法),只不过我们在使用这些计算属性的时候,
//是把它们的名称直接当做属性来使用的,并不会把计算属性当做方法去调用
//注意: 1.计算属性在引用的使用一定不要加()去调用,直接使用就行了
// 2.只有计算属性这个function 内部,所用到的任何data中数据发送了变化,就会立即重新计算这个计算属性
// 3.计算属性的求职结果被缓存起来,方便下次使用
'input3':function(){
console.log("执行几次???")
return this.input1 + '--' + this.input2
}
}
})
//2.methods
new Vue({
el:"#app",
data:{
input1:'',
input2:'',
input3:''
},
methods:{
getinput3(){
this.input3 = this.input1 +"-" + this.input2
}
},
})
//3.watch
new Vue({
el:"#app",
data:{
input1:'',
input2:'',
input3:''
},
methods:{},
watch:{ //使用这个属性,可以监视data中的指定数据改变,然后触发
'input1':function(newVal, oldVal){
//方法1
/* console.log("监视watch!!")
this.input3 = this.input1 +"-" + this.input2 */
//方法2
console.log(newVal+"---****---"+oldVal)
this.input3 = newVal + '-' + this.input2
},
'input2':function(newVal){
//方法2
this.input3 = this.input1 + '-' + newVal
},
}
})