简体   繁体   English

无法获得Vuex突变或采取行动将数据传递给状态

[英]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. 尽管花了几个小时阅读Vuex文档,但我什至不确定我是否正确调用了它们。

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. 我开始创建一个变异,以在触发@click事件时简单地更新我的状态,但是当它不起作用时,我尝试了一个操作并得到了相同的结果:什么都没有。

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: 从我的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. 我知道它不会在我的Vue devtools中返回任何内容,因为它仅显示我的初始状态,并且无法从那里进行手动提交/调度。 Also, console.log statements in both my method and my action aren't being triggered. 另外,不会触发我的方法和操作中的console.log语句。 I've got my store.js file connected to Vue with Vue.use(Vuex); 我已经使用Vue.use(Vuex);将store.js文件连接到Vue 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. 我不确定为什么或如何解决这个问题,但是现在我要更新状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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