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

新手上路,请多包涵

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

我的商店是这样的: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>

原文由 Diego Alves 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 728
2 个回答

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

错误实际上在这里:

应用程序.vue

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

原文由 Diego Alves 发布,翻译遵循 CC BY-SA 3.0 许可协议

也许,您没有在 Vue 实例中包含 store

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

 import store from './store'

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

那么您可以在任何组件中使用 this.$store

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

原文由 Volodymyr Symonenko 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题