Vue Props传值

Props用于父组件向子组件传值

定义类型

javascript 复制代码
// 定义一个接口,用来限制Teacher的属性
export interface Teacher {
  name: string;
  age: number;
  gender: string;
}

export type teacherList = Teacher[];

// 一个自定义类型
export type Teachers = Array<Teacher>;

父组件

html 复制代码
<script lang="ts" setup name="App">
    import Person from './components/Person.vue'

    import { reactive, ref } from 'vue'
    import { type teacherList } from '@/types';

    let personList = reactive<teacherList>([
        { name: '张三', age: 20, gender: '男' },    
        { name: '李四', age: 25, gender: '男' },
        { name: '王五', age: 30, gender: '男' }
    ])
</script>

<template>
  <div class="container">
 	 <!-- <Person a="哈哈" :list="personList"/> -->
     // 不传list,让子组件显示默认数据
    <Person a="哈哈" />
  </div>
</template>

<style scoped>
  .container {
      display: flex;
      height: 100vh; /* 使容器占满整个屏幕高度 */
  }
</style>

子组件

html 复制代码
<script lang="ts" setup name="Person">
    import { type teacherList } from '@/types';

    // let x = defineProps(['a', 'list'])
    // 要先声明才能打印
    // console.log(x.a)

    // 只接受
    // defineProps(['a', 'list'])
    
    // 接受+限制
    // defineProps<{list:teacherList}>()

    // 接受+限制+限制必要性+默认值
    withDefaults(defineProps<{list?:teacherList}>(), 
      {
        // 默认值,这里的默认值也得是teacherList类型,而且是个函数
        list:() => [
          {name:'张三',age:20, gender:'男'},
          {name:'李四',age:25, gender:'女'}
        ]
      }
    )

    
</script>

<template>
  
  <div class="person">
    <!-- <h1>{{ a }}</h1> -->
    <ul>
      <li v-for="item in list" :key="item.name">{{ item.name }} - {{ item.age }}</li>
    </ul>
  </div>
 
</template>

<style scoped>
</style>
相关推荐
贩卖黄昏的熊9 小时前
NestJS简明教程——异常处理和日志
javascript·node.js·nest.js
黄泉路醉s11 小时前
在Vant+Vue+TypeScript的H移动前端使用UnoCSS
前端·vue.js·typescript
海带紫菜菠萝汤12 小时前
FFmpeg.wasm 实践:在浏览器中运行 FFmpeg 的能力边界与性能瓶颈
前端·javascript·ffmpeg·音视频·wasm
名字还没想好☜12 小时前
React 受控输入框光标跳到末尾:格式化输入时的 selection 丢失 bug 与修复
前端·javascript·react.js·bug·react·next.js
upgrador13 小时前
桌面应用开发:Electron 与 NSIS 的关系、打包流程及 Windows 本地构建实战
javascript·windows·electron
我要两颗404西柚13 小时前
Stage three:VUE工程化与实战工具
前端·javascript·vue.js
写不来代码的草莓熊14 小时前
Cesium 地图交互绘制圆形、多边形
前端·javascript·地图
JackSparrow41415 小时前
前端安全之JS混淆+请求加密+请求签名以提升爬虫难度
前端·javascript·后端·爬虫·python·安全
看昭奚恤哭15 小时前
基于 RuoYi-Vue-Pro 定制了一个后台管理系统 magic-admin , 开源出来!
前端·vue.js·开源
kyriewen1 天前
我用AI写了半年代码——回头看,这5个能力正在退化
前端·javascript·ai编程