Vuex存储在mainjs中启动,但在App.vue中未定义

时间:2019-07-04 04:13:41

标签: vue.js vuex

main.js:

import Vue from "vue";
import Axios from "axios";
import App from "./App.vue";
import router from "./router";
import store from "./store";

const axios = Axios.create({
  baseURL: process.env.VUE_APP_BASE_URL
})

Vue.prototype.$http = axios;

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

当我尝试在App.vue中使用$ store时,它是未定义的:

  created() {
    this.$store.dispatch('logout') // this.$store is undefined
  }

store.js:

export default new Vuex.Store({
  actions: {
    logout({commit}) {
      return new Promise((resolve, reject) => {
        commit('logout')
        localStorage.removeItem('token')
        delete Vue.prototype.$http.defaults.headers.common['Authorization']
        resolve()
      })
    }
  }
}

是因为它不是在App.vue中启动的,因为我可以在其他vue组件中使用

3 个答案:

答案 0 :(得分:3)

您尚未在Main.JS中导入Vuex:

import Vuex from 'vuex'
Vue.use(Vuex)

了解有关安装Vuex here的更多信息 编辑:合法的每个人都偷了我的答案...

答案 1 :(得分:3)

import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
    // Options
});

然后放入Vue实例。

希望它对您有帮助。

答案 2 :(得分:0)

首先,您需要使用npm install vuex --save

安装Vuex

然后,将其导入您的store.js

enter image description here

要了解何时为什么如何以使用Vuex,请参考以下URL https://dev.to/napoleon039/when-why-and-how-to-use-vuex-9fl