vue中的計算屬性和偵聽屬性
計算屬性
計算屬性用于處理復雜的業(yè)務邏輯
計算屬性具有依賴性,計算屬性依賴 data中的初始值,只有當初始值改變的時候,計算屬性才會再次計算
計算屬性一般書寫為一個函數(shù),返回了一個值,這個值具有依賴性,只有依賴的那個值發(fā)生改變,他才會重新計算
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <meta http-equiv='X-UA-Compatible' content='ie=edge'> <title>表單輸入綁定</title></head><body> <div id='app'> {{ reverseMsg }}---- {{ reverseMsg }}-------- {{ reverseMsg }} //直接使用計算屬性中的函數(shù)就是所要的數(shù)據(jù) </div></body><script src='http://www.cgvv.com.cn/bcjs/vue.js'></script> //vue的js,不然使用不了vue語法<script> const app = new Vue({ el: ’#app’, data: { msg: ’hello world’ }, computed: { reverseMsg () { // 計算屬性是一個函數(shù),返回一個值,使用和data中的選項一樣 console.log(’computed’) // 執(zhí)行1次 --- 依賴性 return this.msg.split(’’).reverse().join(’’); } } })</script></html>
偵聽屬性(監(jiān)聽屬性)
vue提供了檢測數(shù)據(jù)變化的一個屬性 watch 可以通過 newVal 獲取變化之后的值
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <meta http-equiv='X-UA-Compatible' content='ie=edge'> <title>表單輸入綁定</title></head><body> <div id='app'> <input type='text' v-model='firstname'> + <input type='text' v-model='lastname'> = {{ fullname }} </div></body><script src='http://www.cgvv.com.cn/bcjs/vue.js'></script><script> const app = new Vue({ el: ’#app’, data: { firstname: ’李’, lastname: ’小龍’, fullname: ’李小龍’ }, watch: { // 偵聽屬性 firstname (newVal, oldVal) { // newVal變化之后的值 this.fullname = newVal + this.lastname // 當改變 姓 的時候執(zhí)行 }, lastname (newVal, oldVal) { this.fullname = this.firstname + newVal // 當改變 名字 的時候執(zhí)行 } } })</script></html>
以上就是vue中的計算屬性和偵聽屬性的詳細內(nèi)容,更多關于vue 計算屬性和偵聽屬性的資料請關注好吧啦網(wǎng)其它相關文章!
相關文章:
