将数据从父组件传递到子组件(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>
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/144768.html