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>
相关推荐
蓝黑202016 小时前
Vue的 value=“1“ 和 :value=“1“ 有什么区别
前端·javascript·vue
小李子呢021116 小时前
前端八股6---v-model双向绑定
前端·javascript·算法
史迪仔011216 小时前
[QML] QML IMage图像处理
开发语言·前端·javascript·c++·qt
AI_Claude_code16 小时前
ZLibrary访问困境方案四:利用Cloudflare Workers等边缘计算实现访问
javascript·人工智能·爬虫·python·网络爬虫·边缘计算·爬山算法
Cobyte17 小时前
3.响应式系统基础:从发布订阅模式的角度理解 Vue2 的数据响应式原理
前端·javascript·vue.js
竹林81817 小时前
从零到一:在React前端中集成The Graph查询Uniswap V3池数据实战
前端·javascript
军军君0118 小时前
Three.js基础功能学习十八:智能黑板实现实例五
前端·javascript·vue.js·3d·typescript·前端框架·threejs
Moment18 小时前
AI全栈入门指南:一文搞清楚NestJs 中的 Controller 和路由
前端·javascript·后端
禅思院18 小时前
前端架构演进:基于AST的常量模块自动化迁移实践
前端·vue.js·前端框架