【问题标题】:Mutating state in vuexvuex中的变异状态
【发布时间】:2019-04-30 14:51:25
【问题描述】:

我正在尝试对我的数据库进行 api 调用并提交突变,但我没有取得太大的成功。

Store.js

import Vue from 'vue'
import Vuex from 'vuex' 
import axios from 'axios';

Vue.use(Vuex) 

export const store = new Vuex.Store({  
   state: {
      photons: [],

    },
    mutations: {
      setData(state, value) {
        console.log(value)
        state.photons = value
      }
    },
    actions: {
      async getData(context) {
        const data = await axios.get('10.10.10.1:3000/DB')
        console.log(data)
        context.commit('setData', data)
      },

    }   })

【问题讨论】:

  • 有什么问题?
  • 光子没有被数据填充
  • console.log(data); 打印什么?
  • 你怎么称呼那个动作?
  • @SockMonkey 如果您不调度该操作,那么它就不会运行。把它放在你的初始 Vue 实例的 created() 方法中。

标签: vue.js asynchronous vuejs2 vue-component vuex


【解决方案1】:

在您的 main.js 中尝试在 mounted 钩子中调度该操作:

import Vuex from 'vuex';
import store from './vuex/store';
const app = new Vue({
  el: '#app',
  store,

  mounted() {
    this.$store.dispatch('getData')

  }

});

【讨论】:

  • main.js new Vue({ router, store, mounted() { store.dispatch('getData') }, render: h => h(App), }).$mount('#app'); 给了我这个Error in mounted hook: "TypeError: Cannot read property 'dispatch' of undefined"
  • this.$store.dispatch('getData') 应该可以工作,您是否正确导入了store
猜你喜欢
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 2018-04-16
  • 1970-01-01
  • 2020-02-18
  • 2020-12-18
相关资源
最近更新 更多