vue重methods、computed、watch以及v-model都能偵聽數據,並相應數據的變化
1)methods:每次獲取都會重新計算求值
<div id="app">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" v-model="first" @keypress="change">
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" v-model="last" @keypress="change">
<h2>methods: {{name}}</h2>
</div>
let vm=new Vue({
el:'#app',
data:{
price: 1
},
methods:{
change(){
this.price
}
}
})
2)computed:基於數據依賴進行緩存,只有當數據變化時,纔會重新求值;
<div id="app">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" v-model="first">
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" v-model="last">
<h2>computed: {{cap}}</h2>
</div>
let vm=new Vue({
el:'#app',
data:{
first:'',
last: "",
name:""
},
computed:{
cap:function(){
return this.first+" "+this.last
}
}
})
3)watch:當需要在數據變化時執行異步或者開銷較大的操作時,這個方式最有用;
<div id="app">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" v-model="first">
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" v-model="last">
<h2>watch: {{cap}}</h2>
</div>
let vm=new Vue({
el:'#app',
data:{
first:'',
last: "",
name:""
},
watch:{
first(value){
this.name=value+' '+this.last
},
last(value){
this.name=this.first+" "+value
}
}
})
4)v-model:這是基於數據雙向綁定的
<div id="app">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" v-model="first">
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" v-model="last">
<h2>v-model:{{first+' '+last}}</h2>
</div>