1. 程式人生 > >vue中的computed和methods的區別

vue中的computed和methods的區別

computed與methods

computed是計算屬性的意思,我們在得到最後結果的時候可以使用computed

例如:
<input type="checkbox" v-model="checkAll">
computed: {
checkAll: {
// 當數據變化時會重新計算(取值)
get() {
return this.tableData.every(item => item.isSelect)
},
// val給checkbox賦值時
set(val) {
this.tableData.forEach(item => item.isSelect = val)
},
},
}

methods需要一個事件源來觸發

例如:
<button @click=change" class="btn btn-danger">刪除</button>

methods: {
change(){
this.tableData.forEach(item=>item.isSelect=this.checkAll)
},
}

computed 如果計算的結果不發生改變就不會觸發這個函數,computed會緩存,而methods每次觸發這個事件都會觸發這個函數,computed的性能比methods高

vue中的computed和methods的區別