Vue.js 和 vuex:this.$store 未定义

问题描述 投票:0回答:5

我已经阅读过类似标题的问题,但由于其复杂性,我无法理解它们。我认为使用我的代码会更容易为我找到解决方案。我只会包含相关代码。

我的店铺是这样的: obs:我安装了vuex插件。

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


Vue.use(Vuex)

const state = {
    titulo: "please, change title"
}


const mutations = {
    changeTitle(state, title) {
        state.title= title
    }
}


export default new Vuex.Store({

    state : state,
    mutations : mutations
})

我的应用程序.vue

 <template>
    <div>
      <show-title-component ></show-title-component>
      <change-title-component></change-title-component>
    </div>
</template>

<script>


import ShowTitleComponent from './components/ShowtitleComponent';
import ChangeTitleComponent from './components/ChangeTitleComponent';
import store from './vuex/store';

export default {

components: {ShowTitleComponent, ChangeTitleComponent},
store,
data: function() {
  return {title: 'placeholder'}
}


}
</script>

产生错误的组件:

<template><div>{{ title}}</div></template>

<script>

export default {
    name: "show-title-component",
    computed: {
      title() {
        return this.$store.state.title   /** error   here */
      }
    }
}

</script>
typescript vue.js vuejs2
5个回答
24
投票

也许,您还没有将

store
包含在 Vue 实例中

您的应用程序入口点(app.js 或 main.js 或 index.js)必须包含以下代码:

import store from './store'

new Vue({
 ...
 store,
 ...
})

然后你可以在任何组件中使用

this.$store

但我推荐通用架构:https://vuex.vuejs.org/en/struct.html


6
投票

商店文件应该是Javascript (.js) 文件。更改文件名并重新启动服务器会使 this.$tore 错误消失。

错误实际上就在这里:

应用程序.vue

import store from './vuex/store';  /** in my case, it should be js file. */

4
投票

在你的 main.js 文件中

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import Vuex from 'vuex';
import {store}  from './store'  //use curly braces to around store. 

Vue.config.productionTip = false;

Vue.use(Vuex);

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

这对我有用。


2
投票

就我而言,我使用的是模块。我可以毫无问题地访问突变、操作和吸气剂。但不是国家。解决方案是在使用模块状态时应该使用模块的名称空间进行访问。

查看文档以获取更多信息。

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
 state: { ... },
 mutations: { ... },
 actions: { ... }
}

const store = new Vuex.Store({
    modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> `moduleA`'s state
store.state.b // -> `moduleB`'s state

默认情况下,模块内的操作、突变和 getter 仍然注册在全局命名空间下


1
投票

1.确保将其创建为商店目录

2.

npm i vuex -S

3.确保

src/store/index.js
import Vuex from 'vuex'
Vue.use(Vuex)

4.确保

src/main.js
import store from './store'

© www.soinside.com 2019 - 2024. All rights reserved.