繁体   English   中英

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

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

我使用提供/注入机制将数据从父级传递给孙级,但在我的一个组件中,我需要在将数据发送到模板之前对其进行处理。

所以我有:

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>

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

谢谢。

这对我来说似乎是一个 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()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
    }
  }
})

您在寻找实用程序类型 - 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>,
    },
  }
}

暂无
暂无

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

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