繁体   English   中英

Typescript Vue 组件中的 Pinia 商店给出错误“'CreateComponentPublicInstance' 类型上不存在属性 'testStore'....”

[英]Pinia store in Typescript Vue component gives error "Property 'testStore' does not exist on type 'CreateComponentPublicInstance'...."

我有一个<script setup>块,我在其中导入了我的testStore但是每当我想在我的 vue 文件 vetur 的某个地方使用this.testStore.name时都会给我这个错误:

Property 'testStore' does not exist on type 'CreateComponentPublicInstance<{ [x: string & `on${string}`]: ((...args: any[]) => any) | undefined; } | { [x: string & `on${string}`]: undefined; }, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, ... 10 more ..., {}>'.
  Property 'testStore' does not exist on type '{ $: ComponentInternalInstance; $data: {}; $props: { [x: string & `on${string}`]: ((...args: any[]) => any) | undefined; } | { [x: string & `on${string}`]: undefined; }; ... 10 more ...; $watch(source: string | Function, cb: Function, options?: WatchOptions<...> | undefined): WatchStopHandle; } & { ...; } & ShallowU...'.Vetur(2339)

由于我是打字稿 n00b,我真的不知道如何解决这个问题,而且 Pinia 文档似乎并没有真正帮助我解决这个问题(我只能找到如何为自定义属性制作垫片,但没有关于必须定义我的商店或其他东西)。

这是我的 pinia 商店文件(testStore.ts)

import { defineStore } from 'pinia';

const state = () => ({
  name: 'This is my store'
});

const actions = {};

const getters = {
};
export const useTestStore = defineStore('testStore', {
  state,
  getters,
  actions,
});

这是我的 .vue 文件

<script setup lang="ts">
import { defineComponent } from 'vue'
import { useTestStore } from '@/stores/testStore';
const testStore = useTestStore();
</script>
<template>
  {{ testStore.name }}
</template>
<script lang="ts">
export default defineComponent({
  name: 'testStore',
  mounted () {
    console.log(this.testStore.name)
  }
});
</script>

我认为你的代码应该是

<script setup lang="ts">
  import { defineComponent } from 'vue'
  import { useTestStore } from '@/stores/testStore';
  
  const testStore = useTestStore();

  console.log(testStore); // testStore should displayed
</script>

<template>
  {{ testStore.name }}
</template>

注意:

<script setup lang="ts"></script>

<script lang="ts">
  export default defineComponent({});
</script>

两者都用于定义组件,使用其中之一,不要同时使用。

您可能需要的一些 Vue 文档:

https://vuejs.org/guide/typescript/composition-api.html

https://vuejs.org/guide/typescript/options-api.html

暂无
暂无

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

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