Vuex:存储对象在组件中不可见

时间:2017-03-24 17:15:21

标签: vuejs2 vuex

当我尝试访问随机组件中的vuex存储时,返回undefined。但是,我将商店注入了我的Vue对象。有谁知道如何解决这个问题?我可以手动将商店对象导入到每个组件中,但这不是很干净...... 我的文件看起来像这样:

main.js

import Vue from 'vue'

import VueResource from 'vue-resource'
import VueRouter from 'vue-router'
import VueI18n from 'vue-i18n'

import routes from './config/routes'
import locales from './lang/locales'
import store from './store'

//Routing support
Vue.use(VueRouter);
//Backend support
Vue.use(VueResource);
//Language support
Vue.use(VueI18n);


Vue.config.lang = 'nl';

Object.keys(locales).forEach(function (lang) {
    Vue.locale(lang, locales[lang])
});

const router = new VueRouter({
    store,
    mode: 'history',
    base: '/app/',
    routes: routes
});

new Vue({
    router
}).$mount('#app');

商品/ index.js

import Vue from 'vue'
import Vuex from 'vuex'

import fleet from './modules/fleet'

Vue.use(Vuex)

export default new Vuex.Store({
    modules : {
        fleet
    }
})

app.vue

<template>
    <div id="page-content-wrapper">
        <nav-bar></nav-bar>
        <div class="container-fluid">
            <div class="row">
                <router-view></router-view>
            </div>
        </div>
    </div>
</template>
<script>

    import NavBar from './assets/navBar.vue'
    export default {
        created() {
            console.log(this.$store)
        },
        components: {
            NavBar
        }
    }
</script>

this.$store返回undefined

1 个答案:

答案 0 :(得分:0)

  

const router = new VueRouter({       商店,       模式:&#39;历史&#39;,       基地:&#39; / app /&#39;,       路线:路线});

     

new Vue({       router})。$ mount(&#39;#app&#39;);

商店旨在设置new Vue

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

您已将其放入VueRouter实例中。

合并代码:

const router = new VueRouter({
  routes,
  mode: 'history',
  base: ...
});

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})