Vue.js: 如何访问计算方法中的注入值?

Vue.js: how to access injected value in computed method?

我使用 provide/inject 机制将数据从父级传递给孙子级,但在我的一个组件中,我需要在将数据发送到模板之前处理数据。

所以我有:

export default defineComponent({
  name: 'MrComponent',
  inject: ["mydata"],
  computed: {
    processedData() {
      const mydata = this.mydata;
      return mydata + 1; // Some handling of the data here
    }
  }
})

但我收到以下错误:

[vue-cli-service] TS2339: Property 'mydata' does not exist on type 'CreateComponentPublicInstance<{ [x: string & `on${string}`]: ((...args: any[]) => any) | undefined; } | { [x: string & `on${string}`]: ((...args: never) => any) | undefined; }, { chartOptions: { responsive: boolean; maintainAspectRatio: boolean; cutout: string; borderWidth: number; }; }, ... 15 more ..., {}>'.
[vue-cli-service]   Property 'mydata' does not exist on type '{ $: ComponentInternalInstance; $data: {}; $props: { [x: string & `on${string}`]: ((...args: any[]) => any) | undefined; } | { [x: string & `on${string}`]: ((...args: never) => any) | undefined; }; ... 10 more ...; $watch(source: string | Function, cb: Function, options?: WatchOptions<...> | undefined): WatchStopHan...'.
[vue-cli-service]     41 |   computed: {
[vue-cli-service]     42 |     chartData() {
[vue-cli-service]   > 43 |       const mydata = this.mydata;
[vue-cli-service]        |                           ^^^^^^^^
[vue-cli-service]     44 |     }
[vue-cli-service]     45 |   }
[vue-cli-service]     46 | })

如果我在模板中访问 mydata,它会起作用:

<template>
{{ mydata }}
</template>

但是在显示它之前我需要对我的数据做一些其他操作。正确的做法是什么?

谢谢。

这对我来说似乎是一个 Vue 错误,因为应该从 inject 选项(提交 vuejs/core#5931)中自动检测道具,但有几个解决方法...

选项 1:defineComponent

中的假道具类型

如果您的组件没有 props,您可以通过在 defineComponent() 的第一个类型参数中指定它来“伪造”一个 mydata 道具:

export default defineComponent<{ mydata: number }>({
  inject: ['mydata'],
  computed: {
    processedData() {
      // `this.mydata` is number
    }
  }
})

但是,此解决方法很脆弱,因为它会在您添加 props 选项后立即破坏类型。

选项 2:使用组合 API

将代码的相关部分切换为 Composition API(即 inject() and computed()):

import { defineComponent, inject, computed } from 'vue'

export default defineComponent({
  setup() {
    const mydata = inject('mydata') as number
    const processedData = computed(() => {
      return mydata + 1
    })

    return {
      processedData
    }
  }
})

您在寻找 Utility Types - ComponentCustomProperties 吗?

declare module 'vue' {
  interface ComponentCustomProperties  {
    fastdata: {
      user: {
        nome: string,
        tel: string,
        pts: number,
        nivel: number,
        proximo_nivel: number,
        tot_kg: number,
        coleta: Array<any>,
      },
      noticias: Array<any>,
    },
  }
}