欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 文化 > 第五十八:父传子 defineProps

第五十八:父传子 defineProps

2025/5/12 7:14:00 来源:https://blog.csdn.net/liuxiaojun828/article/details/146046671  浏览:    关键词:第五十八:父传子 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>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词