Vue.js和vuex:这个.$ store未定义

Die*_*ves 10 typescript vue.js vuejs2

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

我的商店是这样的: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
})
Run Code Online (Sandbox Code Playgroud)

我的App.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>
Run Code Online (Sandbox Code Playgroud)

生成错误的组件:

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

<script>

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

</script>
Run Code Online (Sandbox Code Playgroud)

小智 16

也许,你没有包含Vue实例store内部

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

import store from './store'

new Vue({
 ...
 store,
 ...
})
Run Code Online (Sandbox Code Playgroud)

然后你可以this.$store在任何组件中使用

但我推荐一般架构:https://vuex.vuejs.org/en/structure.html 在此输入图像描述


Die*_*ves 6

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

错误实际上在这里:

应用程序.vue

import store from './vuex/store';  /** in my case, it should be js file. */
Run Code Online (Sandbox Code Playgroud)