Vuejs 監聽 vuex 中值的變化

好比說,例如,你有一籃子水果,每次你從籃子裏添加或拿走水果 ,你想顯示有關水果數量的信息,可是你也想當籃子中數量變化的時候收到通知。html

fruit-count-component.vuevue

<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 對象中函數名必須和computed對象中的函數名匹配,在上面實例中名字是 count.vuex

被監視屬性的新值和舊值將做爲參數傳遞到監視回調(count函數)中。api


basket store 看起來像這樣:ide

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

您能夠在如下資源中閱讀更多內容:ui

Computed properties and watchers
API docs: computed
API docs: watchthis

相關文章
相關標籤/搜索