【问题标题】:Use fetch method inside vuex action在 vuex 操作中使用 fetch 方法
【发布时间】:2020-05-12 21:14:01
【问题描述】:

我创建了一个获取 api 的存储操作。当我试图从创建的生命周期钩子中的组件分派它时。我收到Cannot read property 'dispatch' of undefined 错误。我知道有几个类似的问题,但没有一个能解决这个问题。

我也尝试以正常方法发送它,但仍然出现此错误。

store.js

import Vue from "vue";
import Vuex from "Vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    categories: []
  },
  mutations: {
    SET_CATEGORIES(state, categories) {
      state.categories = categories;
    }
  },
  actions: {
    getCategories({ commit }) {
      return fetch("https://api.chucknorris.io/jokes/categories")
        .then(response => {
          return response.json();
        })
        .then(jsonObj => {
          commit("SET_CATEGORIES", jsonObj);
        })
        .catch(error => {
          console.log(error);
        });
    }
  }
});

这是我尝试发送的组件 -

<script>
export default {
  data() {
    return {
      joke: "",
      categories: [],
      selectedCat: ""
    };
  },
  computed: {
    disabled() {
      if (this.joke) {
        return false;
      } else {
        return true;
      }
    }
  },
  methods: {
    addToFavs: function() {
      this.$emit("pushJoke", this.joke);
      this.fetchJoke();
    }

  },

  created() {
    this.$store.dispatch('getCategories');
  }  
};
</script>

我做错了什么?

【问题讨论】:

  • 错误Cannot read property 'dispatch' of undefined 告诉您,问题不在于获取,而在于您的商店。 Vue 组件无法在 store 中找到此操作,如果没有 fetch,它将是相同的事件。
  • 谢谢,根据我的代码有什么理由吗?
  • @KingGary 这是不对的。不是找不到action,而是根本找不到store。 - OP,请在初始化 Vue 对象的任何地方发布 (new Vue({...})) - 这更有可能是问题的根源。
  • 我的猜测是您没有将 store 添加到 Vue 实例中。像这样的东西:const app = new Vue({ el: '#app', store, ... })
  • @KingGary 你说得对,我现在添加了它,错误消失了但 fetch 不起作用,所以现在可能是操作本身的问题。

标签: javascript vue.js


【解决方案1】:

从添加开始

import { mapActions } from 'vuex'

在你的脚本中

然后添加到methods

methods: {
  ...mapActions([
     'getCategories'
  ])
.
.
}

并将您创建的方法更改为

created() {
  this.getCategories()
}  

此外,您可能希望创建一个 vuex 操作来替换您拥有的 this.$emit("pushJoke", this.joke); 行,并以与映射 getCategories 类似的方式映射它

【讨论】:

  • 谢谢,但没有帮助。仍然出现同样的错误。
【解决方案2】:

那是因为您错过了将 vuex 存储选项添加到 Vue 的根实例。解决导入您的商店并将其附加到您的 vue 实例的问题。

import { store } from '.store'

const app = new Vue({
  store
})

【讨论】:

    猜你喜欢
    • 2022-12-10
    • 2022-01-23
    • 2020-11-21
    • 2019-05-27
    • 2017-01-28
    • 2018-01-20
    • 2020-08-14
    • 2020-06-22
    • 1970-01-01
    相关资源
    最近更新 更多