undefinedfix
Sign in

Vuex's problems

Benjamin edited in Fri, 01 Jul 2022

Problem: initial contact with vuex, in this case, the state attribute value of vuex has been modified, but App.vue The computed in is not updated in the page. What's the problem, please?

Details: main.js

import Vue from 'vue'
import Vuex from 'Vuex'
import App from './App'
import store from './store/store.js'

Vue.config.productionTip = false

Vue.use(Vuex)

// eslint-disabled-next-line
/* eslint-disable */
new Vue({
    el: '#app',
    store,
    components: { App },
    template: '<App/>'
})

App . Vue file

<template>
  <div>
    <div>{{count}}</div>
    <div>
      <button v-on:click="add()">+</button>
      <button v-on:click="reduce()">-</button>
    </div>
  </div>
</template>

<script type="text/javascript">
// eslint-disable-next-line
/* eslint-disable */
export default {
  computed: {
    count() {
      return this.$store.state.count;
    }
  },
  methods: {
    add() {
      this.$store.commit("increment");
      console.log(this.count);
    },
    reduce() {
      this.$store.commit("decrement");
      console.log(this.count);
    }
  }
};
</script>
<style>
</style>
store.js
import Vue from 'Vue'
import Vuex from 'Vuex'

Vue.use(Vuex)

/* eslint-disable */
export default new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        increment: state => state.count++,
        decrement: state => state.count--
    }
})
2 Replies
kvlsf
commented on Fri, 01 Jul 2022

Adding events to Vue file does not need add ()

suxbr
commented on Sat, 02 Jul 2022

Mutaions is just a custom event. You need to wake up in actions. In fact, you need to submit the event in actions, and then use the dipatch in the component () To call. Your code should be modified as follows :

export default new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        increment: state => state.count++,
        decrement: state => state.count--
    },
    actions:{
        increment: context => context.commit('increment'),
        decrement: context => context.commit('decrement')
    }
})

main.js There is no need for important vuex from 'vuex'; Vue.use (vuex) these two pieces of code, because you are· store.js ·We have introduced and used vuex in, and then call it in your button event method as follows:

add(){
   this.$store.dispatch('increment')
},
reduce(){
   this.$store.dispatch('decrement')
} 

lock This question has been locked and the reply function has been disabled.