4.vue2-計算屬性computed
阿新 • • 發佈:2019-02-15
Vue計算屬性
Author:vanessa
Date:2018/02/11
計算屬性(computed):通過對data中屬性,進行簡單變換後得到的屬性
例子:
<div id="box"> <div>{{msg}}</div> <div>{{doubleMsg}}</div> </div> <script> new Vue({ el:'#box', data:{ msg:10 }, computed:{ doubleMsg:function(){ return this.msg*2; } } }) </script>
計算屬性和方法
1.計算屬性:具有快取機制,只有他的依賴data中資料發生改變時才會重新求值,多次訪問計算一次
2.方法:訪問幾次執行幾次,不會快取
ps:效能開銷比較大的情況下得到一個計算屬性A,快取後不必多長執行多次消耗
計算屬性和偵聽屬性(watch)
偵聽屬性沒有計算屬性簡潔,不建議使用
var vm = new Vue({ el: '#demo', data: { firstName: 'Foo', lastName: 'Bar', fullName: 'Foo Bar' }, watch: { firstName: function (val) { this.fullName = val + ' ' + this.lastName }, lastName: function (val) { this.fullName = this.firstName + ' ' + val } } })
var vm = new Vue({
el: '#demo',
data: {
firstName: 'Foo',
lastName: 'Bar'
},
computed: {
fullName: function () {
return this.firstName + ' ' + this.lastName
}
}
})
Vue 提供了一種更通用的方式來觀察和響應 Vue 例項上的資料變動:偵聽屬性。當你有一些資料需要隨著其它資料變動而變動時,你很容易濫用 watch——特別是如果你之前使用過 AngularJS。然而,通常更好的做法是使用計算屬性而不是命令式的 watch 回撥。
計算屬性的 setter
計算屬性預設只有 getter ,不過在需要時你也可以提供一個 setter :
<div>{{users}}</div>
var vm=new Vue({
el:'#box',
data:{
msg:10,
user:{
name:"tom",
age:2
}
},
computed:{
users:{
get:function(){
return 'my name is '+this.user.name+',I am '+this.user.age+' year old';
},
set:function(val){
var arr=val.split(' ');
this.user.name=arr[0];
this.user.age=arr[1];
}
},
reverseMsg:function(){
return this.msg*2;
}
}
})
vm.users='jerry 1'
偵聽器
watch 偵聽資料變化。當需要在資料變化時執行非同步或開銷較大的操作時,這個方式是最有用的。
<div>
<div><input v-model="question"><div>
<div>{{answer}}<div>
</div>
data:{
question: '',
answer:'ask a question'
},
watch:{
question: function(newQuestion, oldQuestion) {
this.answer = 'Waiting for you to stop typing...';
this.getAnswer();
}
},
methods:{
getAnswer: function() {
if (this.question.indexOf('?') === -1) {
this.answer = 'Questions usually contain a question mark. ;-)'
return
}
this.answer = 'Thinking...'
var vm = this
axios.get('https://yesno.wtf/api')
.then(function (response) {
vm.answer = (response.data.answer)
})
.catch(function (error) {
vm.answer = 'Error! Could not reach the API. ' + error
})
}
}