繁体   English   中英

Vuex this.$store 未定义

[英]Vuex this.$store is undefined

我正在尝试使用 vux 和 vuetify 学习 vue。 我已经通过 vue cli 安装了它。

就像在文档中一样,我尝试访问商店,但未定义 this.$storage。

src/components/HelloWorld.vue

<script>

export default {
  methods: {
    onChangeTheme: () => {
      console.log(this.$store)
    }
  }
};
</script>

src/main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import vuetify from './plugins/vuetify';

Vue.config.productionTip = false

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

src/store.js

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {

  },
  mutations: {

  },
  actions: {

  }
})

不要在选项属性或回调上使用箭头函数,例如created: () => console.log(this.a)vm.$watch('a', newValue => this.myMethod()) 由于箭头函数没有 this,因此 this 将被视为任何其他变量并通过父作用域进行词法查找直到找到,通常会导致错误,例如 Uncaught TypeError: Cannot read property of undefined 或 Uncaught TypeError: this.myMethod不是函数。

这是解释here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM