第五十八:父传子 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>
相关推荐
Ruihong35 分钟前
Vue3 转 React:组件透传 Attributes 与 useAttrs 使用详解|VuReact 实战
vue.js·react.js
是江迪呀35 分钟前
实时看大家都在干嘛?我靠一行监听函数,做了个轻互动小程序
前端·微信小程序
QCzblack41 分钟前
BugKu BUUCTF ——Reverse
java·前端·数据库
gwjcloud41 分钟前
基于linux下docker部署前端vue项目
前端·javascript·vue.js
小李子呢02111 小时前
前端八股CSS(1)---响应式布局的方法
前端·css
小李子呢02112 小时前
前端八股Vue(6)---v-if和v-for
前端·javascript·vue.js
程序员buddha2 小时前
ES6 迭代器与生成器
前端·javascript·es6
周周记笔记2 小时前
初识HTML和CSS(一)
前端·css·html
aq55356002 小时前
网页开发四剑客:HTML/CSS/JS/PHP全解析
javascript·css·html
程序员buddha2 小时前
TypeScript详细教程
javascript·ubuntu·typescript