this.$store 未定义以下示例应用程序结构 [英] this.$store is undefined following example application structure

查看:22
本文介绍了this.$store 未定义以下示例应用程序结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Vuex,如应用程序结构文档中所示.但是,$store 未显示在 Vue 开发工具中,并在我的代码中返回 undefined.我使用了 购物车 示例作为参考.

I'm trying to use Vuex as shown in the application structure documentation. However, $store isn't showing in Vue dev tools and returning undefined in my code. I've used the shopping cart example as a reference.

import Vue from 'vue/dist/vue';
import store from './store';
import router from './router';

const app = new Vue({
  el: '#app',

  store,
  router,

  computed: {
    loading() {
      return this.$store.state.application.loading.active;
    }
  }
});

在 store/index.js(按照示例布局)我有:

In store/index.js (following the example layout) I have:

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

import application from './modules/application';

Vue.use(Vuex);

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

最后在 store/modules/application.js:

And finally in store/modules/application.js:

const state = {
  loading: {
    active: true,
    message: ''
  },
  syncing: {
    active: false,
    message: ''
  }
}

const getters = {
  //
}

const actions = {
  //
}

const mutations = {
  /**
   * Update Loading
   * 
   * @param {*} state 
   * @param {string} appState
   * @param {boolean} active 
   * @param {string} message 
   */
  updateAppState(state, appState = false, active = false, message = '') {
    if (Object.keys(state).includes(appState)) {
      state.appState = {
        active: active,
        message: message
      }
    }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

请注意,我正在一个类似的庄园中导入我的路由器实例并且它正在工作,router/index.js:

Note i'm importing my router instance in a similar manor and it's working, router/index.js:

import Vue from 'vue/dist/vue';
import VueRouter from 'vue-router';

import ContentDefault from '../components/main/ContentDefault';

Vue.use(VueRouter);

export default new VueRouter({
  routes: [
    {
      // Default view
      path: '/',
      components: {
        default: ContentDefault
      },
    }
  ]
});

附带问题,无法访问子组件中的 $store,这是因为我在主应用程序和商店文件中导入了不同版本的 Vue,vue 而不是 vue/dist/vue

Side issue, wasn't able to access $store in child components, it was because I was importing a different version of Vue in my main app and store files, vue instead of vue/dist/vue

推荐答案

您的应用程序中不需要 $ 常量.由于您刚刚导入商店,您可以直接使用它.

You don't need the $ in your app const. And since you've just imported store you can use it directly.

尝试以下操作:

import Vue from 'vue/dist/vue';
import store from './store';
import router from './router';

const app = new Vue({
  el: '#app',

  store,
  router,

  computed: {
    loading() {
      return store.state.application.loading.active;
    }
  }
});

这篇关于this.$store 未定义以下示例应用程序结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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