Vue3 typescript 中使用<component> 渲染多个动态组件类型报错

首先看官网渲染多个组件的的示例代码:

<script setup lang="ts">
import Home from './Home.vue'
import Posts from './Posts.vue'
import Archive from './Archive.vue'
import { ref } from 'vue'

const currentTab = ref('Home')

const tabs = {
  Home,
  Posts,
  Archive
}
onMounted(() => {
  console.log(tabs)
})
</script>

<template>
  <div class="demo">
    <button
      v-for="(_, tab) in tabs"
      :key="tab"
      :class="['tab-button', { active: currentTab === tab }]"
      @click="currentTab = tab"
    >
      {{ tab }}
    </button>
    <***ponent :is="tabs[currentTab]" class="tab"></***ponent>
  </div>
</template>

<style>
.demo {
  font-family: sans-serif;
  border: 1px solid #eee;
  border-radius: 2px;
  padding: 20px 30px;
  margin-top: 1em;
  margin-bottom: 40px;
  user-select: none;
  overflow-x: auto;
}

.tab-button {
  padding: 6px 10px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  border: 1px solid #***c;
  cursor: pointer;
  background: #f0f0f0;
  margin-bottom: -1px;
  margin-right: -1px;
}

.tab-button:hover {
  background: #e0e0e0;
}

.tab-button.active {
  background: #e0e0e0;
}

.tab {
  border: 1px solid #***c;
  padding: 10px;
}
</style>
<template>
  <div class="tab">
    Archive ***ponent
  </div>
</template>

<template>
  <div class="tab">
    Home ***ponent
  </div>
</template>

<template>
<div class="tab">
  Posts ***ponent
  </div>
</template>
<script setup lang="ts">
</script>

此时这里会报错

元素隐式具有 "any" 类型,因为类型为 "string" 的表达式不能用于索引类型 "{ Home: Define***ponent<{}, {}, {}, {}, {}, ***ponentOptionsMixin, ***ponentOptionsMixin, {}, string, PublicProps, Readonly<ExtractPropTypes<{}>>, {}, {}>; Posts: Define***ponent<...>; Archive: Define***ponent<...>; }"。
在类型 "{ Home: Define***ponent<{}, {}, {}, {}, {}, ***ponentOptionsMixin, ***ponentOptionsMixin, {}, string, PublicProps, Readonly<ExtractPropTypes<{}>>, {}, {}>; Posts: Define***ponent<...>; Archive: Define***ponent<...>; }" 上找不到具有类型为 "string" 的参数的索引签名。ts-plugin(7053)

这是因为类型的原因出错,此时我们给 tabs 加一个类型约束就可以解决,如下:

const tabs: Record<string, any> = {
  Home,
  Posts,
  Archive
}

在TypeScript中,Record<K, T>是一个实用类型,用于创建一个新对象类型,其键是类型K的成员,值是类型TRecord<K, T>接受两个类型参数:

  1. K:键类型的联合。在这个例子中,string被用作键类型,意味着tabs对象的键可以是任何字符串。
  2. T:值类型。在这个例子中,any被用作值类型,意味着tabs对象的每个键对应的值可以是任何类型。 
转载请说明出处内容投诉
CSS教程网 » Vue3 typescript 中使用<component> 渲染多个动态组件类型报错

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买