【问题标题】:Uncaught (in promise) TypeError: Cannot read property '$store' of undefinedUncaught (in promise) TypeError: Cannot read property '$store' of undefined
【发布时间】:2021-06-08 15:28:39
【问题描述】:

我想用 vue3 和 vuex 构建一个应用程序。我在使用 $store 时遇到错误(Uncaught (in promise) TypeError: Cannot read property '$store' of undefined)。但我没有找到任何相关信息。你能帮帮我吗?

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import { store } from "./store";

createApp(App)
  .use(store)
  .use(router)
  .mount("#app");

main.js

<template>
  {{ posts }}
  <button @click="clickOnButton">Tıkla</button>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  computed: {
    posts: () => this.$store.state.post
  },
  methods: {
    clickOnButton: () => {
      this.$store.commit("getPost");
    }
  }
};
</script>

组件

【问题讨论】:

标签: vue.js vuex store


【解决方案1】:

问题与您的商店无关。当您应该使用标准方法语法时,您正在使用箭头函数:

// ...
  methods: {
    clickOnButton() {
      // this will now point to your component.
      this.$store.commit('getPost');
    }
  }
// ...

箭头函数的最大限制是它们完全不受上下文影响:this 不受约束。见vue documentation

还有arrow functions documentation

箭头函数表达式是传统函数表达式的紧凑替代方案,但受到限制且不能在所有情况下使用。

差异与限制:

  • 没有自己的与thissuper 的绑定,不应用作方法。

【讨论】:

猜你喜欢
  • 2019-02-12
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-07
相关资源
最近更新 更多