在我的Vue代码中,当尝试运行VueX映射的操作时,我收到以下错误消息:
[TypeError:无法读取未定义的属性'dispatch'
我被困在this.retrieveProducts();
请参考下面的屏幕截图,以了解我发现的错误。
Screenshot of the error message
我正在使用Django,Webpack和Vue-Cli3。
App.vue
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> |
<router-link to="/product-list">Products</router-link>
</div>
</div>
</template>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
#nav {
padding: 30px;
}
#nav a {
font-weight: bold;
color: #2c3e50;
}
#nav a.router-link-exact-active {
color: #42b983;
}
</style>
main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import { mapState, mapGetters, mapMutations,mapActions } from 'vuex';
Vue.config.productionTip = false;
new Vue({
router,
store,
methods: {
...mapMutations([
'loadProducts',
]),
...mapActions([
'retrieveProducts', // **FAILS HERE (Step-2)**
'saySomething',
]),
testCall: () => { // Works here
alert('You are in removeLink');
},
},
computed: {
...mapState([
'products',
'products_images',
]),
...mapGetters([
]),
},
mounted() {
alert('mounting now'); // Works here
this.testCall(); // Works here
this.retrieveProducts(); // **FAILS HERE (Step-1)**
},
render: h => h(App),
}).$mount('#app');
index.js .. \ store
import Vuex from 'vuex';
import axios from 'axios';
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';
export default new Vuex.Store({
state: {
products: [],
products_images: [],
},
mutations: {
loadProducts: (state, {products, products_images}) => {
state.products = products;
state.products_images = products_images;
},
},
actions: {
retrieveProducts: () => {
alert("I NEED TO EXECUTE CODE HERE"); // **FAILS HERE (Step-3)**
},
},
getters: {
}
});
答案 0 :(得分:0)
您需要使用Vue.use(Vuex)
安装Vuex插件。
答案 1 :(得分:0)
添加缺少的代码后,代码可以正常工作
import Vue from 'vue';
Vue.use(Vuex);
index.js .. \ store
import Vue from 'vue'; // added now
import Vuex from 'vuex';
import axios from 'axios';
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';
Vue.use(Vuex); // added now
export default new Vuex.Store({
state: {
products: [],
products_images: [],
},
mutations: {
loadProducts: (state, {products, products_images}) => {
state.products = products;
state.products_images = products_images;
},
},
actions: {
retrieveProducts: () => {
alert("I NEED TO EXECUTE CODE HERE"); // **FAILS HERE (Step-3)**
},
},
getters: {
}
});