Vue语法学习第三课——计算属性
生活随笔
收集整理的這篇文章主要介紹了
Vue语法学习第三课——计算属性
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
模板內(nèi)的表達式非常便利,但是設(shè)計它們的初衷是用于簡單運算的。在模板中放入太多的邏輯會讓模板過重且難以維護。對于任何復(fù)雜邏輯,都應(yīng)當(dāng)使用計算屬性。
<div id="example"><p>original message : "{{message}}"</p><p>computed reversed message : "{{reverseMessage}}"</p></div><script>var vm = new Vue({el:"#example",data:{message : "zxq"},computed : {reverseMessage : function(){return this.message.split('').reverse().join('');}}});</script>?同樣的效果也可以通過在表達式中調(diào)用methods實現(xiàn)。
注:計算屬性是基于他們的依賴進行緩存的,只有在相關(guān)依賴發(fā)生改變時,計算屬性才會重新求值。
如上示例,只有當(dāng)message改變時,多次訪問?reverseMessage 計算屬性才會再次執(zhí)行函數(shù),否則會返回之前的結(jié)果。
而對比methods,總是會再次執(zhí)行函數(shù)。
?
computed 和 watch
<div id="app0">firstname : <input type="text" v-model="firstName"/><br/>lastname : <input type="text" v-model="lastName"/><p>my name is : {{fullName}}</p> </div>?
① watch
var vm = new Vue({el: '#app0',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}}})?
?
② computed
var vm = new Vue({el: '#app0',data: {firstName: 'Foo',lastName: 'Bar'},computed: {fullName: function () {return this.firstName + ' ' + this.lastName}}})?
相比之下,計算屬性更為簡潔
?
計算屬性默認只有g(shù)et方法,但在必要時也可以提供一個set方法
<div id="example">firstname : <input type="text" v-model="firstName"/><br/>lastname : <input type="text" v-model="lastName"/><br/>my name is : <input v-model="fullName" /></div><script>var vm = new Vue({el:"#example",data: {firstName: 'zhu',lastName: 'xingqing'},computed : {fullName : {get : function(){return this.firstName + ' ' + this.lastName},set : function(newVal){newfull = newVal.split(' ');this.firstName = newfull[0];this.lastName = newfull[1];}}}});</script>?
轉(zhuǎn)載于:https://www.cnblogs.com/zhuxingqing/p/10502052.html
總結(jié)
以上是生活随笔為你收集整理的Vue语法学习第三课——计算属性的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 平安信用卡优享金和备用金区别在哪里?哪个
- 下一篇: 工商银行信用卡现金分期手续费多少?申请有