【发布时间】: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