watch 監聽某個數據的變化(監聽完調用什麼函數) 一個數據影響多個數據 (好比:瀏覽器自適應、監控路由對象、監控自身屬性變化)瀏覽器
watch: { firstName(val) { this.fullName = val + this.lastName } } computed: { fullName() { this.firstName + this.lastName; } }
watch 場景:緩存
一、自適應瀏覽器(監聽瀏覽器寬高、若是有變化就存在localStorage裏面去,或者有變化就通知其餘組件改變化)app
data() { return { height: '' } }, mounted() { const _this = this this.height = document.documentElement.clientHeight localStorage.setItem('whVal', JSON.stringify({'height': this.height })) window.onresize = function temp() { _this.height = document.documentElement.clientHeight } }, watch: { // 若是發生改變,這個函數就會運行 height() { this.changeFixed(this.width, this.height) // eventBus.$emit('onresize', {'height': this.height }) 或者通知其餘組件變化 } }, methods: { changeFixed(width, height) { // 動態修改樣式 localStorage.setItem('Layout', JSON.stringify({'height': height })) } }
二、監控路由對象函數
new Vue({ el: '#app', router: router, //開啓路由對象 watch: { '$route': function(newroute, oldroute) { console.log(newroute, oldroute); //能夠在這個函數中獲取到當前的路由規則字符串是什麼 //那麼就能夠針對一些特定的頁面作一些特定的處理 } } })
computed 場景:this
一、做爲過濾器:展開更多spa
<li v-for="(item,index) in addressListFilter" :class="{'check':checkIndex == index}" @click="checkIndex=index;selectedAddrId=item._id"></li> <a @click="expand" v-bind:class="{'open':limit>3}">展開更多</a> data(){ return { addressList:[], // 地址列表 limit:3, // 限制默認顯示3個地址 checkIndex:0 } }, computed:{ addressListFilter(){ return this.addressList.slice(0,this.limit); } }, methods:{ expand(){ // 點擊more更多 if(this.limit ==3){ this.limit = this.addressList.length; }else{ this.limit =3; } } } }
二、做爲過濾器:tab切換code
<span v-for="(item,index) in navList" :key="index" @click="type = index" :class="{'active':type===index}">{{item}}</span> <li v-for="(item,index) in taskListfilter" :key="index"> </li> data() { return { navList: ['所有', '實時單', '競價單'], type:0, taskList:[] } }, computed: { taskListfilter() { switch (this.type) { case 0:return this.taskList case 1:return this.taskList.filter(item => item.type === '實時單') case 2:return this.taskList.filter(item => item.type === '競價單') // default :return this.taskList } } }