为什么 $store 没有定义?

ste*_*eve 5 javascript vue.js vuex

我正在努力使用 vuejs 和 vuex 开发一个项目,但它无法this.$store.state.count在组件中使用。为什么?

我的配置:

"vuex": "^2.0.0"
Run Code Online (Sandbox Code Playgroud)

商店.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
})
Run Code Online (Sandbox Code Playgroud)

main.js:

import store from './vuex/store'
import Vue from 'vue'

new Vue({
  store,
  .
  .
  .
}).$mount('#app')
Run Code Online (Sandbox Code Playgroud)

组件.js:

<script>
export default {
    name: 'landing-page',
    created: () => {
      console.log('status2')
      console.log(this.$store.state.count)
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

错误:

Uncaught TypeError: Cannot read property '$store' of undefined
Run Code Online (Sandbox Code Playgroud)

joa*_*umg 5

您永远不会直接编辑商店。

你总是会触发突变。

像这样(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>
Run Code Online (Sandbox Code Playgroud)