例如,假设您有一篮水果,每次在篮子中添加或删除水果时,您都希望(1)显示有关水果数量的信息,但您还希望(2)以某种花哨的方式收到水果计数的通知......
fruit-count-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
监视属性的新值和旧值将作为参数传递到监视回调(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
您可以在以下资源中阅读更多内容: