第五十八:父传子 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>
相关推荐
Rockson3 分钟前
使用Ruby接入实时行情API教程
javascript·python
祝余呀15 分钟前
HTML初学者第三天
前端·html
就爱瞎逛31 分钟前
TailWind CSS Intellisense 插件在VSCode 上不生效
前端·css·vscode·tailwind
柚子81634 分钟前
sibling-index:我用这个画时钟表盘
前端·css
UI设计和前端开发从业者1 小时前
UI前端大数据处理策略优化:基于云计算的数据存储与计算
前端·ui·云计算
前端小巷子1 小时前
Web开发中的文件上传
前端·javascript·面试
翻滚吧键盘2 小时前
{{ }}和v-on:click
前端·vue.js
上单带刀不带妹2 小时前
手写 Vue 中虚拟 DOM 到真实 DOM 的完整过程
开发语言·前端·javascript·vue.js·前端框架
前端风云志2 小时前
typescript结构化类型应用两例
javascript
杨进军2 小时前
React 创建根节点 createRoot
前端·react.js·前端框架