将数据从父组件传递到子组件(Props)
子组件
我们先来创建一个子组件
<template> <div class="child"> <h3>{{title}}</h3> <p>{{content}}</p> </div> </template> <script setup lang="ts"> //从父级接收数据,定义接口 interface Props { title: string; content: string } //defineProps() 加上定义的接口名称 // defineProps<Props>(); const propsData = defineProps<Props>(); console.log('propsData',propsData.title,propsData.content) </script>
以上代码,我们从父级接收到数据,并定义了数据接口,然后使用defineProps() 加上定义的接口名称。也可以定义一个propsData参数来打印出数据。
父组件
<template> <child-comp title="学习vue3" :content="content" /> </template> <script setup> import ChildComp from "../../components/ChildComp.vue"; import {ref} from "vue"; const content = ref('一起来学习vue3吧') </script>
将数据从子组件传递到父组件(Emit)
子组件
<template> <div class="child"> <h3>{{title}}</h3> <p>{{content}}</p> <button @click="buttonClick">点击获取数据</button> </div> </template> <script setup lang="ts"> //从父级接收数据,定义接口 interface Props { title: string; content: string } //defineProps() 加上定义的接口名称 const propsData = defineProps<Props>(); console.log('propsData',propsData.title,propsData.content) //给传给父组件的数据定义一个接口 interface Emits { (event:"sendMessage",msg:msg) : void; } const emit = defineEmits<Emits>(); //定义一个msg的数据 const msg = '这是从子组件传到父组件的数据' const buttonClick = () => { emit("sendMessage",msg) } </script>
父组件
<template> <child-comp title="学习vue3" :content="content" @sendMessage="getMessage"/> </template> <script setup> import ChildComp from "../../components/ChildComp.vue"; import {ref} from "vue"; const content = ref('一起来学习vue3吧') //在父组件接收子组件传过来的数据 const getMessage = (msg) => { console.log('msg',msg) } </script>