【发布时间】:2018-09-18 22:02:31
【问题描述】:
尝试在组件中使用 Vuex 状态。
这工作正常:main.js:
const store = new Vuex.Store({
state: {
counter: 1
},
mutations: {
increment(state) {
state.counter++
}
}
})
new Vue({
store,
render: h => h(App)
}).$mount('#app')
和内部组件:<span>{{this.$store.state.test}}</span>
当我尝试将 Vuex 移动到单独的 store.js 时,它不起作用。store.js(就在 main.js 附近):
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
counter: 1
},
mutations: {
increment(state) {
state.counter++
}
}
})
在组件内部我进行导入:
import store from '../store',
比尝试使用:
<span>{{store.state.test}}</span>
我得到了
实例上没有定义属性或方法“store”
<span>{{this.$store.state.test}}</span> 结果
Uncaught ReferenceError: store is not defined
我尝试将export default new Vuex.Store({...}) 更改为export const store = new Vuex.Store({...}),但没有帮助。
P。 S. 这对我有用:
内部组件:
computed: {
counter() {
return store.state.counter
}
}
和<span>{{counter}}</span>.
但是不使用computed 属性还有其他方法吗?因为我使用 Vuex 来全局调用它的状态,而这里我必须在任何地方的每个组件中定义computed...
【问题讨论】:
-
对于您的第二个用例,您没有将 store 实例绑定到 Vue 实例,因此它不会像
<span>{{store.state.test}}</span>那样工作,就像this.store.state.test,但this.store将是未定义的。