简体   繁体   English

在 vuex 操作中使用 fetch 方法

[英]Use fetch method inside vuex action

I created a store action that fetch api.我创建了一个获取 api 的商店操作。 When I'm trying to dispatch it from component in created lifecycle hook.当我尝试从创建的生命周期钩子中的组件分派它时。 I'm getting Cannot read property 'dispatch' of undefined error.我收到无法read property 'dispatch' of undefined错误的read property 'dispatch' of undefined I know there are several similar questions but none of them solved this issue.我知道有几个类似的问题,但没有一个解决了这个问题。

I tried to dispatch it also in normal method and still get this error.我也尝试以正常方法发送它,但仍然出现此错误。

store.js商店.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);
        });
    }
  }
});

And this is the component which I try to dispatch in -这是我尝试分派的组件 -

<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>

What am I doing wrong?我究竟做错了什么?

Start by adding从添加开始

import { mapActions } from 'vuex'

in your script在你的脚本中

then add to methods然后添加到methods

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

and alter your created method to并将您创建的方法更改为

created() {
  this.getCategories()
}  

Furthermore, you might want to create a vuex action to replace that this.$emit("pushJoke", this.joke);此外,您可能想要创建一个 vuex 操作来替换this.$emit("pushJoke", this.joke); line that you have, and map that in a similar way that you have mapped getCategories行,并以与映射getCategories类似的方式映射它

That's because you missed to add your vuex store option to the root instance of Vue.那是因为您没有将 vuex 存储选项添加到 Vue 的根实例。 To solve that import your store and attach it to your vue instance.要解决该问题,请导入您的商店并将其附加到您的 vue 实例。

import { store } from '.store'

const app = new Vue({
  store
})

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

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