最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is $store not defined? - Stack Overflow

programmeradmin0浏览0评论

I am struggling to developed a project with vuejs and vuex, but it does not work with this.$store.state.count in the ponent. 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')

ponent.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

I am struggling to developed a project with vuejs and vuex, but it does not work with this.$store.state.count in the ponent. 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')

ponent.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
Share Improve this question edited Dec 9, 2016 at 15:46 steve asked Dec 9, 2016 at 15:39 stevesteve 1,4285 gold badges17 silver badges26 bronze badges 4
  • 6 The error does not mean that $store is not defined. Read carefully. It says that this is not defined. – Sebastian Simon Commented Dec 9, 2016 at 15:41
  • Oh, yes. this is undefined. Why can't I use this here ? – steve Commented Dec 9, 2016 at 15:45
  • this in the ponent will refer to it's data. – joaumg Commented Dec 9, 2016 at 15:46
  • Oh, I see. Thank you. – steve Commented Dec 9, 2016 at 15:50
Add a ment  | 

2 Answers 2

Reset to default 5

You will never, ever edit the store directly.

You will ALWAYS trigger mutations.

As so (ponent.js):

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

export default {
  name: 'landing-page',
  puted: {
    counter () {
      return store.state.count // get state
    }
  },
  created: () => {
    store.mit('increment') // set state
  }
}
</script>

That is because this in arrow function is not what you expect as this in "normal function". You can refer to Arrow functions or Javascript ES6 — Arrow Functions and Lexical this for more information

发布评论

评论列表(0)

  1. 暂无评论