当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Why is $store not defined?

问题描述:

I am struggling to developed a project with vuejs and vuex, but it does not work with this.$store.state.count in the component. Why?

My config:

"vuex": "^2.0.0"

store.js:

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({

state: {

count: 12

},

mutations: {

increment (state) {

state.count++

}

},

strict: true

})

main.js:

import store from './vuex/store'

import Vue from 'vue'

new Vue({

store,

.

.

.

}).$mount('#app')

component.js:

<script>

export default {

name: 'landing-page',

created: () => {

console.log('status2')

console.log(this.$store.state.count)

}

}

</script>

Error:

Uncaught TypeError: Cannot read property '$store' of undefined

网友答案:

You will never, ever edit the store directly.

You will ALWAYS trigger mutations.

As so (component.js):

<script>
import store from './vuex/store'

export default {
  name: 'landing-page',
  computed: {
    counter () {
      return store.state.count // get state
    }
  },
  created: () => {
    store.commit('increment') // set state
  }
}
</script>
分享给朋友:
您可能感兴趣的文章:
随机阅读: