第五十八:父传子 defineProps

父传子:传字符串 和 对象 模式

<script setup>

import { reactive } from 'vue';

import HelloWorld from './components/HelloWorld.vue'

const per = reactive([  // 这里 reactive 传的是响应式数据

{id:1,name:"张三"},

{id:2,name:"李四"}

])

// 这不是响应式数据:

/*

const propsWeb = {

user: 10,

ip: '127.0.0.1'

}

*/

</script>

<HelloWorld msg="Vite + Vue888888888888" :per = per />  // 传递数据

// msg 传递的是字符串

// :per 传递的是对象

子接收数据:

定义一个:defineProps // 宏参数

defineProps({

msg: String,

per:Object

})

接收变量:

<template>

<h1>{{ msg }}</h1>

<h2>{{ per }}</h2>

</template>

App.vue

复制代码
<script setup>
  import { reactive } from 'vue'

  //导入子组件
  //App.vue是父组件,因为它包含了header.vue和footer.vue两个子组件
  import Header from "./components/header.vue"
  import Footer from "./components/footer.vue"

  /*
  const propsWeb = {
    user: 10,
    ip: '127.0.0.1'
  }
  */
  //响应式数据
  const propsWeb = reactive({
    user: 10,
    ip: '127.0.0.1'
  })

  //添加用户
  const userAdd = () => {
    propsWeb.user++
    console.log(propsWeb.user)
  }
</script>

<template>
  <!-- 父传子 - 方式1 -->
  <Header propsName="邓瑞编程" propsUrl="dengruicode.com" />

  dengruicode.com

  <button @click="userAdd">添加用户</button>

  <!-- 父传子 - 方式2 -->
  <!-- <Footer v-bind="propsWeb" /> -->
  <Footer :="propsWeb" />
</template>

<style scoped></style>

header.vue

复制代码
<script setup>
    //子组件

    //接收方式1 - 数组
    /*
        defineProps是Vue3的编译时宏函数,
        用于接收父组件向子组件传递的属性(props)

        注
        当使用Vue编译器编译包含defineProps的组件时,
        编译器会将这些宏替换为相应的运行时代码
    */
    const props = defineProps(["propsName","propsUrl"])
    console.log(props)
</script>

<template>
    <h3>Header</h3>
</template>

<style scoped>

</style>

footer.vue

复制代码
<script setup>
    //子组件

    //接收方式2 - 对象
    /*
    const props = defineProps({
        user: Number,
        ip: String
    })
    */
    const props = defineProps({
        user: Number,
        ip: {
            type: String,
            required: true, //true表示必传属性,若未传则会提示警告信息
            default: 'localhost' //未传默认值
        }
    })

    console.log(props)
</script>

<template>
    <h3>Footer</h3>
    user: {{ props.user }}
</template>

<style scoped>

</style>
相关推荐
一 乐6 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
C_心欲无痕6 小时前
ts - tsconfig.json配置讲解
linux·前端·ubuntu·typescript·json
清沫6 小时前
Claude Skills:Agent 能力扩展的新范式
前端·ai编程
yinuo7 小时前
前端跨页面通信终极指南:方案拆解、对比分析
前端
北辰alk7 小时前
Vue 模板引擎深度解析:基于 HTML 的声明式渲染
vue.js
北辰alk7 小时前
Vue 自定义指令完全指南:定义与应用场景详解
vue.js
yinuo7 小时前
前端跨页面通讯终极指南⑨:IndexedDB 用法全解析
前端
北辰alk8 小时前
Vue 动态路由完全指南:定义与参数获取详解
vue.js
北辰alk8 小时前
Vue Router 完全指南:作用与组件详解
vue.js
北辰alk8 小时前
Vue 中使用 this 的完整指南与注意事项
vue.js