4. 計算屬性和監視
阿新 • • 發佈:2020-08-16
計算屬性
- 在 computed 屬性物件中定義計算屬性的方法
- 在頁面中使用{{方法名}}來顯示計算的結果
監視屬性
- 通過通過 vm 物件的$watch()或 watch 配置來監視指定的屬性
- 當屬性變化時, 回撥函式自動呼叫, 在函式內部進行計算
計算屬性高階
- 通過 getter/setter 實現對屬性資料的顯示和監視
- 計算屬性存在快取, 多次讀取只執行一次 getter 計算
編碼
<div id="demo"> 姓: <input type="text" placeholder="First Name" v-model="firstName"><br> 名: <input type="text" placeholder="Last Name" v-model="lastName"><br> 姓名 1(單向): <input type="text" placeholder="Full Name" v-model="fullName1"><br> 姓名 2(單向): <input type="text" placeholder="Full Name" v-model="fullName2"><br> 姓名 3(雙向): <input type="text" placeholder="Full Name2" v-model="fullName3"><br> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> var vm = new Vue({ el: '#demo', data: { firstName: 'Kobe', lastName: 'bryant', fullName2: 'Kobe bryant' }, computed: { fullName: function () { return this.firstName + " " + this.lastName }, fullName3: { get: function () { return this.firstName + " " + this.lastName }, set: function (value) { var names = value.split(' ') this.firstName = names[0] this.lastName = names[1] } } }, watch: { lastName: function (newVal, oldVal) { this.fullName2 = this.firstName + ' ' + newVal } } }) vm.$watch('firstName', function (val) { this.fullName2 = val + ' ' + this.lastName })