【问题标题】:Vuejs and Webpack: Why is store undefined in child componentsVuejs 和 Webpack:为什么在子组件中未定义存储
【发布时间】:2018-12-17 16:40:21
【问题描述】:

我正在使用带有 Webpack 的 Vuejs。

这里是 store.js:

import Vuex from "vuex";

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

这是我的 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 的脚本:

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

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

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

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

     import Vue from "vue";
     import Vuex from "vuex";
    
     Vue.use(Vuex);
    

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

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

    store.js:

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

    MyComponent.vue<script> 块:

    export default {
        mounted() {
            console.log(this.$store); // will log the store instance
        }
    }
    

    index.js:

    import Vue from "vue";
    import Vuex from "vuex";
    
    import store from "./store";
    import MyComponent from "./components/MyComponent.vue";
    
    Vue.use(Vuex);
    
    const app = new Vue({
        el: "#my-app"
        store,
        components: { MyComponent },
        // any other options as needed
    });
    

    【讨论】:

    • 这在官方 Vue Discord 服务器上多次向 OP 解释过,但拒绝接受 Vue.use() 的使用。不幸的是,OP 会忽略你的问题。
    • @user9993 我知道,但是在服务器上,OP 似乎正在寻找解释为什么它是必要的,除了“它就是这样”之外没有人提供。 OP 似乎对出口的运作方式也有一些误解,我试图解决这个问题。
    【解决方案2】:

    您应该在 store.js 中添加这两行

    import Vue from "vue";
    
    Vue.use(Vuex);

    如果不实际说出上面的第二条语句,就无法实例化 store。所以,你需要在你的store.js 中导入Vue

    【讨论】:

      【解决方案3】:

      好的,所以我想走这条路的原因是将商店代码与应用程序的其余部分分开。

      我已经设法通过从store.js 导出一个默认对象来做到这一点,其中该对象只是商店的配置(即不是商店实例)。然后我使用导入的配置在我的app.js 中实例化商店。

      如果有人想提供一种导出/导入实例本身的方法,我会将这个答案保留几天。

      【讨论】:

        猜你喜欢
        • 2021-03-12
        • 2018-08-17
        • 2020-07-18
        • 2022-01-12
        • 1970-01-01
        相关资源
        最近更新 更多