比如說,例如,你有一籃子水果,每次你從籃子里添加或拿走水果 ,你想顯示有關(guān)水果數(shù)量的信息,但是你也想當(dāng)籃子中數(shù)量變化的時候收到通知。
fruit-count-component.vue
<template> <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, yaay!`) } } } </script>
上述代碼,請注意,watch 對象中函數(shù)名必須和computed對象中的函數(shù)名匹配,在上面實例中名字是 count.
被監(jiān)視屬性的新值和舊值將作為參數(shù)傳遞到監(jiān)視回調(diào)(count函數(shù))中。
basket store 看起來像這樣:
fruit-basket.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 } } // Obvously you would need some mutations and actions, // but to make example cleaner I'll skip this part. }) export default basket
您可以在以下資源中閱讀更多內(nèi)容:
Computed properties and watchers
API docs: computed
API docs: watch
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com