watch 監聽某個數據的變化(監聽完調用什么函數) 一個數據影響多個數據 (比如:瀏覽器自適應、監控路由對象、監控自身屬性變化)
computed 計算后返回新 一個數據受多個數據影響(比如:計算總價格、過濾某些數據)
computed是用來處理你使用watch和methods的時候無法處理(比如有緩存的時候監聽不了數據變化),或者是處理起來並不太恰當的情況的,利用computed處理methods存在的重復計算情況
watch: {
firstName(val) { this.fullName = val + this.lastName }
}
computed: {
fullName() { this.firstName + this.lastName; }
}
watch 場景:
1、自適應瀏覽器(監聽瀏覽器寬高、如果有變化就存在localStorage里面去,或者有變化就通知其他組件改變化)
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 }))
}
}
2、監控路由對象
new Vue({
el: '#app',
router: router, //開啟路由對象
watch: {
'$route': function(newroute, oldroute) {
console.log(newroute, oldroute);
//可以在這個函數中獲取到當前的路由規則字符串是什么
//那么就可以針對一些特定的頁面做一些特定的處理
}
}
})
computed 場景:
1、作為過濾器:展開更多
<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;
}
}
}
}
2、作為過濾器:tab切換
<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
}
}
}

