Vue语法学习第三课——计算属性
生活随笔
收集整理的這篇文章主要介紹了
Vue语法学习第三课——计算属性
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
模板內的表達式非常便利,但是設計它們的初衷是用于簡單運算的。在模板中放入太多的邏輯會讓模板過重且難以維護。對于任何復雜邏輯,都應當使用計算屬性。
<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>?同樣的效果也可以通過在表達式中調用methods實現。
注:計算屬性是基于他們的依賴進行緩存的,只有在相關依賴發生改變時,計算屬性才會重新求值。
如上示例,只有當message改變時,多次訪問?reverseMessage 計算屬性才會再次執行函數,否則會返回之前的結果。
而對比methods,總是會再次執行函數。
?
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}}})?
相比之下,計算屬性更為簡潔
?
計算屬性默認只有get方法,但在必要時也可以提供一個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>?
轉載于:https://www.cnblogs.com/zhuxingqing/p/10502052.html
總結
以上是生活随笔為你收集整理的Vue语法学习第三课——计算属性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 平安信用卡优享金和备用金区别在哪里?哪个
- 下一篇: 浅谈Vue之双向绑定