ts在项目中的使用defineProps

99 阅读1分钟

ts在项目中的使用defineProps

<script lang="ts" setup>
import TsDemo from '@/components/TsDemo.vue'
import { type PersonDataList } from '@/types'
import { reactive, ref } from 'vue'

let count = ref(0)

let personLists = reactive<PersonDataList>([
  {
    name: '马六',
    age: 25,
    //怎么设置一个接口属性可有可无呢,在接口属性名后面加上?
    sex: '男'
  },
  {
    name: '小黄',
    age: 20
  }
])
</script>

<template>
  <div>
    <div class="person">
      <h1>viteDemo</h1>
      <h2 ref="title">标签内容</h2>
    </div>
    <!--    注意在组件中活着标签中使用:表示使用的是表达式,没有:都表示字符串,ref除外-->
    <TsDemo :list="personLists" :count="count" />
  </div>
</template>
<style>
button {
  margin: 10px 10px;
}
</style>
<script setup lang="ts">
import type { PersonDataList } from '@/types'

//注意在vue3中define开头的都是宏定义,不需要引入,全局可以使用

//只接收list,同时将props保存起来
// let x = defineProps(['list'])

//接收list,count
//  defineProps(['list', 'count'])

//接收list+限制类型,同时将props保存起来
// let x =defineProps<{ list: PersonDataList }>()

//接收list+(PersonDataList)限制类型+(list?)限制必要性+指定默认值
withDefaults(defineProps<{ list?: PersonDataList }>(), {
  list: () => [
    {
      name: '小灰',
      age: 20
    }
  ]
})
</script>

<template>
  <div>
    <h1>{{ list[0].name }}</h1>
    <h2>{{ list[0].age }}</h2>
  </div>
</template>
<style scoped></style>