【问题标题】:Default Vuex project, return this.$store.state error默认 Vuex 项目,返回 this.$store.state 错误
【发布时间】:2021-06-17 18:07:23
【问题描述】:

return this.$store.state.counter 完全错误:

类型“CreateComponentPublicInstance'.Vetur(2339)

“CreateComponentPublicInstance, ... 5 个 ..., {}>'.Vetur(2339)


这是一个干净的 Vue 项目(vue create v-vuex),具有以下 CLI 配置:

  • Vue 3.x(预览版)
  • 类风格的组件语法
  • Yes 与 TypeScript 一起使用 Babel
  • ESLint + Prettier linter 和格式化程序
  • 保存时 Lint
  • 专用配置文件

所有文件都是通过 Vue CLI 创建的默认文件,具有默认项目结构

index.ts 文件:

import { createStore } from "vuex";

export default createStore({
  state: {
    counter: 8,
  },
  mutations: {},
  actions: {},
  modules: {},
});

App.vue 文件:

<template>
  <h2>{{ counter }}</h2>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "App",
  components: {},
  computed: {
    counter() {
      return this.$store.state.counter;
    },
  },
});
</script>

main.ts 文件:

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

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


我正在学习 Vue,我想访问 Vuex 存储状态属性。基本计数器示例。

只有当我通过模板中的插值(例如{{ $store.state.counter }})直接使用计数器状态时,我才能访问它,但是一旦我想使用一个返回的计算属性,我就无法访问 $store关键字 this

return this.$store.state.counter 不起作用


我的编码设置:

  • VSCode,最新版本
  • NPM 和 Vue CLI
  • 维图尔
  • ESLint
  • 更漂亮


我在不同的项目设置中做过相同的示例,例如“无 TypeScript”和“使用 Class-Style 组件语法”,但在前一种情况下,我的 Vetur 则无法正常工作,因此无法接受(不确定它是否会出错),在后一种情况下,它可以工作,但我不熟悉语法,而且由于我没有经验,甚至考虑学习类风格来解决这个问题都是压倒性的。


编辑:有类似的问题,但没有一个与新的 Vue CLI 项目有关。

【问题讨论】:

    标签: typescript vue.js vuex this vetur


    【解决方案1】:

    试试这个

    export default createStore({
      state() {
        return : {
          counter: 8,
        }
      },
      mutations: {},
      actions: {},
      modules: {},
    });
    
    counter: function () {
      return this.$store.state.counter;
    },
    

    工作代码:https://codesandbox.io/s/vue-3-ionic-vuex-forked-w571p?file=/src/App.vue

    【讨论】:

    • 这不起作用并在 IDE 中产生更多错误。
    • 这段代码对我来说可以正常工作,没有问题吗?示例项目在哪里,所以我可以看看...我用代码链接编辑了我的答案
    猜你喜欢
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 2019-09-26
    • 1970-01-01
    • 2020-05-02
    • 2018-08-19
    相关资源
    最近更新 更多