【问题标题】:Vuex doesn't work as expected - problem with import?Vuex 无法按预期工作 - 导入问题?
【发布时间】: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 将是未定义的。

标签: vue.js vuex


【解决方案1】:

您的导出和导入不遵循 ES6 规则, 如果您使用的是export const store = new Vuex.Store({...}) 您需要像这样导入

import {store} from '../store.js'

如果没有,请将您的代码更新为:

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

Vue.use(Vuex)

export default const store = new Vuex.Store({   state: {
    counter: 1   },   mutations: {
    increment(state) {
      state.counter++
    }   } })

【讨论】:

  • export default const store = new Vuex.Store({...}) 似乎语法错误,至少它不能编译...
  • 我去了export const store = new Vuex.Store({...})import {store} from '../store.js',但仍然无法访问组件模板内的store
【解决方案2】:

我是这样走的:
store.js:

export default new Vuex.Store({...})

main.js:

import store from './store'

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

比在任何组件的模板中:<span>{{this.$store.state.counter}}</span>

无法确认这是最好的方法,但它对我有用。

【讨论】:

  • 好的,如果它对你有用,那就没问题了。
猜你喜欢
  • 2019-02-06
  • 2019-11-24
  • 2021-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
  • 2018-04-02
  • 1970-01-01
相关资源
最近更新 更多