[英]How to create a Utils class for Vue.js that has access to Vuex this.$store
[英]Vue.js and vuex: this.$store is undefined
我已经阅读过类似标题的问题,但由于它们的复杂性,我无法遵循它们。 我认为使用我的代码会更容易为我找到解决方案。 我只会包括相关的代码。
我的商店是这样的: 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
})
我的 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>
产生错误的组件:
<template><div>{{ title}}</div></template>
<script>
export default {
name: "show-title-component",
computed: {
title() {
return this.$store.state.title /** error here */
}
}
}
</script>
也许,你还没有在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
商店文件应该是 Javascript (.js) 文件。 更改文件名并重新启动服务器会使 this.$tore 错误消失。
错误实际上在这里:
应用程序
import store from './vuex/store'; /** in my case, it should be js file. */
在您的 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");
这对我有用。
就我而言,我使用的是模块。 我可以毫无问题地访问突变、动作和吸气剂。 但不是国家。 解决方案是在使用模块状态时应该使用模块的命名空间进行访问。
查看文档以获取更多信息。
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.确保你创建了一个商店目录
2. npm i vuex -S
3.确保src/store/index.js
已经import Vuex from 'vuex'
和Vue.use(Vuex)
import Vuex from 'vuex'
4.确保src/main.js
有import store from './store'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.