【问题标题】:Fetch data from endpoint using vuex action and set store variables in vuex?使用 vuex 操作从端点获取数据并在 vuex 中设置存储变量?
【发布时间】:2020-12-08 13:01:06
【问题描述】:

我需要从端点获取数据,然后将数据分配给存储中的状态变量。

代码看起来像这样。

import Vue from 'vue'
import axios from 'axios'

import Vuex from 'vuex'
Vue.use(Vuex)

export const store = new Vuex.Store({
    state: {
      sample: 'foo',
      sample2 : [],
      sample3: []
    },
    getters:{
    },
    actions:{
      getData(context){
        axios.get('/endpoint').then(function(response){
          console.log(context.state);
          console.log(context.state.sample);
          console.log(response);
          context.state.sample = 'bar';
          console.log(context.state.sample);
          context.state.sample2 = response.data.sample2data;
          context.state.sample3 = response.data.sample3data;
        }
        );
      }
    },
    mutations:{
    }
});

据我所知,问题在于应用程序根本不执行 axios 请求。我已经在其他地方测试了端点,我确定请求本身没有问题。当然,每次挂载我的应用程序时都应该执行请求?

【问题讨论】:

  • 你在哪里执行这个动作?
  • 在 store.js 文件中。我将商店导出到创建 vue 应用程序的 main.js 文件。据我所知,这是一种标准模式。
  • 应该从你的组件中调用一个动作来执行。将 store.js 导出到 main.js 只是告诉 vue 你将使用这个文件作为一个搅拌器
  • 啊,我明白了。我需要在应用程序级别执行操作,因为我希望这些数据始终可供所有组件使用。有没有办法做到这一点?
  • 它会因为它保存在状态中

标签: vue.js axios vuex flux


【解决方案1】:

在您的App.jsmounted 方法中,您可以这样做

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

【讨论】:

    【解决方案2】:

    您需要在创建 vue 实例的 created 方法中调度操作。如果在组件中调度操作,则仅在安装组件之后注入存储。数据只会在安装组件后加载,这意味着需要读取数据的组件可以访问它,但是状态中的数据在加载时将是未定义的。

    export const store = new Vuex.Store({
        state: {
          sample2 : [], // undefined
          sample3: []  // undefined
        },
        getters:{
        },
        actions:{
          getData(context){
            axios.get('/endpoint').then(function(response){
              context.state.sample2 = response.data.sample2data;
              context.state.sample3 = response.data.sample3data;
            }
            );
          }
        },
        mutations:{
        }
    });
    

    以下确保在安装任何组件之前调度操作,因此组件将能够在 操作正确设置值之后读取状态

    import {store} from 'path/to/store/';
    
    new Vue({
      el: '#app',
      computed:,
      store: store,
      created() {
        this.$store.dispatch('getData') // dispatch loading
      }
    })
    
    

    【讨论】:

      猜你喜欢
      • 2020-12-23
      • 2021-11-03
      • 2022-01-05
      • 2021-05-15
      • 2021-12-07
      • 1970-01-01
      • 2020-06-27
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多