我有一个<script setup>
块,我导入我的testStore
,但每当我想使用this.testStore.name
在我的vue文件vetur给我这个错误:
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)
因为我是一个typescript n00b我真的不知道如何解决这个问题,并且Pinia文档似乎并没有真正帮助我解决这个问题(我只能找到如何为自定义属性制作一个shim,但没有关于必须定义我的商店或其他东西)。
这是我的pinia store文件(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