计算值无法识别道具对象

Computed value does not recognize prop object

我想做的是创建一个计算值以便在我的视图中使用,因此 Documentation 我尝试:

我有一个组件,我将数组对象发送为:

const tabs = ref([
      {
        imageSrc: '/programs/test1.png',
         ....
      },

在其他组件中,我收到的是:

export default defineComponent({
  name: 'ProgramModal',

  props: {
    tabs: {
      type: Array as PropType<Array<any>>,
      required: true,
    },
  },


  computed: {
    img() {
      return `./images/modal/${encodeURIComponent(this.tabs.imageSrc)}.png`
    },
  },

})

如您所见,我有一个计算值抛出了两个错误,一个在 img 中,另一个在 this.tabs.imageSrc 中:

第一个错误:

img implicitly has return type any because it does not have a return type annotation and is referenced directly or indirectly in one of its return expression

第二个错误:

Property tabs does not exist on type { img(): any; }

我做错了什么?此致

有两个问题:

  1. TypeScript 对选项 API 的支持有 known limitation that requires annotating return types on computed:

    Because of the circular nature of Vue’s declaration files, TypeScript may have difficulties inferring the types of certain methods. For this reason, you may need to annotate the return type on methods like render and those in computed.

    所以你应该注释return类型的img():

    img(): string {
              
      return `...`
    }
    

    如果不修复此错误,组件实例的类型推断将中断,导致您观察到的错误:Property tabs does not exist on type { img(): any; }.

  2. 正如此处删除的答案中所指出的,this.tabs 是一个数组,但是您的计算道具试图直接从数组中读取 imageSrc,而实际上它应该来自数组元素。要读取第一个数组元素的 imageSrc,请使用带有零索引 (this.tabs[0].imageSrc) 的方括号:

    return `./images/modal/${encodeURIComponent(this.tabs[0].imageSrc)}.png`
                                                          
    

您的代码应与此类似:

export default defineComponent({
  computed: {
    img(): string {
      return `./images/modal/${encodeURIComponent(this.tabs[0].imageSrc)}.png`
    },
  },
})