Search code examples
javascriptvue.jsvuexvue-router

Vue: The best practice to change value in the component nested in the Vue Router using Vuex


I am new to Vue, Vue Router, and Vuex.

Please advise the best practice to change/update values in the component nested in the Vue Router, using Vuex store. I wrote a simple code to change the number in the component by hitting the button but seems not working properly.

The following is the code I made:

// Trying to change the value in the component, 
// but not updating the DOM, only the value in the state
function incrementValueInComponent(){
    store.commit('increment');
    alert("number in the store is: " + store.state.testNumber);
}

// *** Vuex store ***
const store = new Vuex.Store({
    state: {
        testNumber: 0
    },
    mutations: {
      increment (state) {
        state.testNumber++
      }
    }
});

// *** Component and Vue router ***
const Foo = { 
    store:store,
    data(){
        return {
            myNumber:this.$store.state.testNumber
        }
    },
    template: '<div>{{myNumber}}</div>' ,
}
const routes = [
  { path: '/', component: Foo }
]
const router = new VueRouter({
  routes
})

const app = new Vue({
  router
}).$mount('#app')
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- Vue, Vuex, Vue router-->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/vuex"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
    <div id="app">
        <h1>Hello App!</h1>
        <p>
          <router-link to="/">Top Page</router-link>
        </p>
        <router-view></router-view>
        <button class="btn" onclick="incrementValueInComponent()">Increment Number</button>
    </div>
    <script src="javascript.js"></script>
</body>
</html>

Am I doing something wrong or is this approach something against the concept of the Vue? Any advice would be appreciated. Thanks in advance.


Solution

  • use computed

    const Foo = { 
        store:store,
        computed: {
            myNumber () {
                return this.$store.state.testNumber
            }
        }
        template: '<div>{{myNumber}}</div>' ,
    }