How to watch store values from vuex ?

How to watch store values from vuex ?

Asked on November 15, 2018 in vue.js.
Add Comment


  • 2 Answer(s)
      •  For example you have a basket of fruits, and each time you add or remove a fruit from the basket.

     

      • Then you want to display about fruit count, But you want to be notified of the count of the fruits in some fashion 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, yaay!`)
            }
        }
    }
    </script>
    
      • Please note, that the name of the function in the watch object, will be matching.
      • The name of the function in the computed object.
      • In the example above the name is count.
      • New and old values of a watched property will be passed into watch callback (the count function) as parameters.

     

    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
    
    Answered on November 15, 2018.
    Add Comment
      • You should not use component’s to listen and  to state change.
      • I recommend you to use getters functions and then map them inside your component.

     

    import { mapGetters } from 'vuex'
    export default {
        computed: {
            ...mapGetters({
            myState: 'getMyState'
            })
        }
    }
    
    • In your store:
    const getters = {
        getMyState: state => state.my_state
    }
    

     

    Answered on November 15, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.