vue3中组合式 API_为 reactive() 标注类型

发布时间 2023-07-21 13:14:45作者: 商品部-林军

image-20230130180528305

reactive() 也会隐式地从它的参数中推导类型

<template>
 <h3>{{ book.title }}</h3>
 <h3>{{ book.author }}</h3>
</template>
<script setup lang="ts"> import { reactive } from "vue" const book = reactive({ title:"三体", author:"刘慈欣" }) book.title = 200 // Type 'number' is not assignable to type 'string' </script>

要显式地标注一个 reactive 变量的类型,我们可以使用接口

<template>
 <h3>{{ book.title }}</h3>
 <h3>{{ book.author }}</h3>
</template>

<script setup lang="ts">
import { reactive } from "vue"
interface iBook{
 title:string;
 author?:string
}
const book:iBook = reactive({
 title:"三体",
 author:"刘慈欣"
})
</script>

数组处理

<template>
 <ul>
  <li v-for="(item,index) in books" :key="index">
   <h3>{{ item.name }}</h3>
   <p>{{ item.v }}</p>
  </li>
 </ul>
</template>
<script setup lang="ts">
import { reactive } from "vue"
interface Item{
 name:string;
 v:number
}
interface iBooks{
  [index:number]:Item
}
const books:iBooks = reactive([
  {
  name:"流浪地球",
  v:1
  },
  {
  name:"黑暗森林",
  v:2
  },
  {
  name:"死神永生",
  v:3
  }
])
</script>