简体   繁体   中英

Cannot get Vuex mutation or action to pass data to state

I cannot get either a mutation or action to pass data to the app state. I'm not even sure if I'm calling them correctly, despite having spent a couple of hours reading the Vuex docs.

I started out creating a mutation to simply update my state when an @click event is fired, but when it didn't work, I tried an action and got the same result: nothing.

Example of how I'm calling the action:

<div v-for="(data, index) in dataList" :key="index">
  <div @click="updateDataSomewhereElse(data)">  // action called here
    // do some other stuff
  </div>
</div>

Example of how I'm dispatching the action from my single-file component:

// some code
methods: {
  updateDataSomewhereElse: function(data) {
    this.$store.dispatch('setData', data); // action dispatched here
  }
}

Example of my action and mutation:

// state code
mutations: {
  updateStateData(state, data) {
    state.data = data;
  }
},
actions: {
  setData({commit}, data) {
    commit('updateStateData', data);
  }
}

Needless to say, I'm expecting my state to be updated with my mutation when my action gets called, but I'm not getting anything.

What have I done wrong?

Edit - More Details:

Example of my initial state:

state: {
  data: 'something'
}

From my main.js:

import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app');

I know it's not returning anything in my Vue devtools as it only shows my initial state and I can't do a manual commit/dispatch from there. Also, console.log statements in both my method and my action aren't being triggered. I've got my store.js file connected to Vue with Vue.use(Vuex); , so it's not an issue of connection.

I fixed this issue by simply doing this:

<div v-for="(data, index) in dataList" :key="index">
  <div>
    <span @click="updateDataSomewhereElse(data)">do some other stuff</span>
  </div>
</div>

I'm not sure why or how this is the answer, but I'm now getting my state to update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM