計算屬性的應用
- 對於輸入框模糊搜索,動態監聽改變數組(使用過濾器)
- 計算屬性計算時所依賴的屬性一定是響應式依賴,否則計算屬性不會執行
- 計算屬性是基於依賴進行緩存的,就是說在依賴沒有更新的情況,調用計算屬性並不會重新計算,可以減少開銷
<template>
<input type="text" v-model="query" />
<li
v-for="(item, index) in computedList"
v-bind:key="item.msg"
v-bind:data-index="index"
>
{{ item.msg }}
</li>
</template>
data(){
return {
query:'',
list:[
{ msg: 'Bruce Lee' },
{ msg: 'Jackie Chan' },
{ msg: 'Chuck Norris' },
{ msg: 'Jet Li' },
{ msg: 'Kung Fury' }
]
}
}
computed:{
computedList:function(){ //動態改變computedList的數組
var that = this;
return that.list.filter((el) => {
return el.msg.toLowerCase().indexOf(that.query.toLowerCase()) !== -1 //返回數組框所包含的數組
})
}
},
2.輸入框始終輸入大寫
<template>
<input v-model="value2Computed" />
</template>
data(){
return {
value2: "",
}
}
computed:{
value2Computed: {
get: function () {
return this.value2;
},
set: function (val) {
this.value2 = val.toUpperCase();
}
},
}