例如,假设您有一篮子水果,每次从篮子中添加或移除水果时,您希望 (1) 显示有关水果数量的信息,但您还希望 (2) 收到通知以某种奇特的方式计算水果的数量……
水果计数component.vue
<template>
<!-- We meet our first objective (1) by simply -->
<!-- binding to the count property. -->
<p>Fruits: {{ count }}</p>
</template>
<script>
import basket from '../resources/fruit-basket'
export default () {
computed: {
count () {
return basket.state.fruits.length
// Or return basket.getters.fruitsCount
// (depends on your design decisions).
}
},
watch: {
count (newCount, oldCount) {
// Our fancy notification (2).
console.log(`We have ${newCount} fruits now, yay!`)
}
}
}
</script>
请注意,watch
对象中的函数名称必须与对象中的函数名称匹配computed
。在上面的例子中,名称是count
.
监视属性的新旧值将作为参数传递到监视回调(计数函数)中。
篮子商店可能看起来像这样:
水果篮.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const basket = new Vuex.Store({
state: {
fruits: []
},
getters: {
fruitsCount (state) {
return state.fruits.length
}
}
// Obviously you would need some mutations and actions,
// but to make example cleaner I'll skip this part.
})
export default basket
您可以在以下资源中阅读更多内容: