【问题标题】:Vuex this.$store is undefinedVuex this.$store 未定义
【发布时间】:2019-12-29 12:03:23
【问题描述】:

我正在尝试使用 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: {

  }
})

【问题讨论】:

  • 当您尝试使用箭头函数作为 vue 方法时,您将丢失引用 vue 实例的 this 的上下文。注意不建议这样做,你应该使用正常的函数声明
  • 非常感谢,这将解决我的问题。

标签: vue.js vuex


【解决方案1】:

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

这是解释here

【讨论】:

  • 非常感谢。是否可以使用箭头函数并将商店作为参数传递?类似于:``` onChangeTheme: ({store}) => store.someData```
猜你喜欢
  • 2018-08-01
  • 2018-11-23
  • 2018-07-25
  • 2019-10-01
  • 2019-11-04
  • 1970-01-01
  • 2021-07-06
  • 2020-03-03
  • 2022-08-15
相关资源
最近更新 更多