Vuejs 和 Webpack:为什么在子组件中未定义存储 [英] Vuejs and Webpack: Why is store undefined in child components

查看:32
本文介绍了Vuejs 和 Webpack:为什么在子组件中未定义存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Vuejs 和 Webpack.

I am using Vuejs with Webpack.

这是 store.js:

Here's store.js:

import Vuex from "vuex";

export default new Vuex.Store({
    state: {
        count : 0
    },
    mutations: {
        increment (state) {
            state.count++
        }
    }
});

这是我的 app.js:

Here is my app.js:

"use strict";

import Vue from 'vue';

window.Vue = Vue;
import MyComponent from './MyComponent.vue';
import store from './store.js';

window.App = new Vue({
    el : '#my-app',
    store,
    components : {
        'my-component' : MyComponent
    }
});

这是来自 MyComponent.vue 的脚本:

Here is the script from MyComponent.vue:

export default {
    computed : {
        count() {
            return this.$store.state.count;
        }
    },
    mounted() {
        console.log(this.$store)
    }
}

在我的组件中对 this.$store 的任何引用都是未定义的.为什么?

Any reference to this.$store in my component is undefined. Why?

推荐答案

您需要在某处安装 Vuex 插件以允许 Vue 组件访问商店.正如 Pavan 指出的那样,要做到这一点,您必须在某处包含以下几行(在您的应用程序的 index.js 中,在您的 store.js 等中)在创建 Vue 实例之前:

You need to install the Vuex plugin somewhere to allow Vue components to access the store. As Pavan noted, to do this you must include the following lines somewhere (in your app's index.js, in your store.js etc) before you create your Vue instance:

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

 Vue.use(Vuex);

这会告诉 Vue 在您创建实例时如何处理 store 实例,这将使其在组件中的 this.$store 下可用.这也确保了 Vuex 也知道如何与 Vue 交互.没有它,您将无法正确使用 Vue 和 Vuex.

This tells Vue what to do with the store instance when you create the instance, which will make it available under this.$store in your components. This also ensures that Vuex also knows how to interact with Vue. Without it, you will not be able to use Vue and Vuex together properly.

关于您稍后的回答,您可以导出商店实例就好了,并将其导入到您的index.js、路由器配置等中.例如:

Regarding your later answer, you can export the store instance just fine, and import it into your index.js, router config etc. For example:

store.js:

 import Vuex from "Vuex";

 export default new Vuex.Store({ /* store config */ });

MyComponent.vue

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆