使用 Typescript 注入 Vue 3

Mar*_* G. 5 typescript vue.js vuejs3

我使用了新的 Vue 3 Composition API 并为响应式数据编写了一个“存储”。

const state = reactive<State>({
  accessToken: undefined,
  user: undefined,
});

export default {
  state: readonly(state),
}
Run Code Online (Sandbox Code Playgroud)

在创建应用程序时,我向所有组件提供商店:

const app = createApp(App)
  .provide("store", store)
  .use(IonicVue)
  .use(router);
Run Code Online (Sandbox Code Playgroud)

最后在一个组件/视图中,我注入了 store 来使用它。

export default defineComponent({
  name: "Home",
  inject: ["store"],
  components: {
    IonContent,
    IonHeader,
    IonPage,
    IonTitle,
    IonToolbar,
    IonButton,
  },
  computed: {
    email() {
      return this.store.state.user.email;
    },
  },
});
</script>
Run Code Online (Sandbox Code Playgroud)

不幸的是,Typescript 不喜欢this.store计算属性中使用的方式email()

并说

类型“ComponentPublicInstance<{}、{}、{}、{ email(): any;”上不存在属性“store”;}, {}, EmitsOptions, {}, {}, false, ComponentOptionsBase<{}, {}, {}, { email(): any; }、{}、ComponentOptionsMixin、ComponentOptionsMixin、EmitsOptions、字符串、{}>>'

我的意思是一切正常,当我删除lang="ts"<script/>标签,但没有显示错误。关于如何解决这个问题或它特别意味着什么的任何建议?

提前致谢!

Luc*_*ebs 10

对于那些使用 Vue 3 + TS 处理相同问题的人,我找到了一个解决方案,而无需更改app.config或声明新的module

  1. App.ts 设置
import { createApp, reactive } from 'vue'
import App from './App.vue'

const Store = reactive({
  myProperty: 'my value'
})

createApp(App)
  .provide('Store', Store)
  .mount('#app')
Run Code Online (Sandbox Code Playgroud)
  1. 访问注入的反应对象的组件:
<template>
  <div>{{ Store.myProperty }}</div>
</template>

<script lang="ts">
import { IStore } from '@/types'
import { defineComponent, inject } from 'vue'

export default defineComponent({
  name: 'MyComponentName',
  setup() {
    return {
      Store: inject('Store') as IStore,
    }
  },
  created() {
    console.log(this.Store) // will show the `Store` in the console
  }
})
</script>
Run Code Online (Sandbox Code Playgroud)
  1. Store ( @/types.ts) 的类型定义:
export interface IStore {
  myProperty: string
}
Run Code Online (Sandbox Code Playgroud)

Store.myProperty按照这 3 个步骤,我可以使用 TypeScript 毫无问题地读取/写入


Bou*_*him 5

我建议使用 store 作为全局属性而不inject在任何子组件中指定 the ,因为提供/注入可能有一些反应性警告:

const app = createApp(App)
  .use(IonicVue)
  .use(router);
app.config.globalProperties.store= store;

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties  {
       store:any // replace it with the right type
     }
   }
Run Code Online (Sandbox Code Playgroud)

然后直接使用它:

export default defineComponent({
  name: "Home",
  components: {
  ...
  },
  computed: {
    email() {
      return this.store.state.user.email;
    },
  },
});
</script>
Run Code Online (Sandbox Code Playgroud)