父传子
基本思想:1.父组件中给子组件绑定属性;2.子组件内部通过props选项接收数据
代码展示:
在APP组件中,引入父组件并在<template>标签中使用
父组件:
<template>
<h3>我是父组件</h3>
<!-- 1.绑定响应式属性:msg -->
<child :msg="message" />
</template>
<script setup>
import { ref } from "vue";
//导入子组件
import child from "./child.vue";
const message = ref("父组件传递的信息");
</script>
子组件:
<template>
<h3>我是子组件</h3>
<h3>{{ msg }}</h3>
</template>
<script setup>
// 通过编译器宏defineProps接收父组件传递的数据
defineProps({
msg: String,
});
</script>
浏览器展示:
子传父
基本思想:1.父组件中给子组件标签通过@绑定事件 2.子组件内部通过自定义方法触发事件
代码展示:
在APP组件中,引入父组件并在<template>标签中使用
父组件:
<template>
<h3>{{ title }}</h3>
<!-- 1.绑定自定义事件 -->
<child1 @toSonChild="childMessage" />
</template>
<script setup>
import { ref } from "vue";
// 引入子组件
import child1 from "./child1.vue";
const title = ref("我是父组件");
const childMessage = (data) => {
title.value = data;
};
</script>
子组件:
<template>
<h3>我是子组件</h3>
<button @click="passMessage">向父组件传递参数</button>
</template>
<script setup>
// 通过编译器宏defineEmits生成changeFather(可以自己更换)方法
const changeFather = defineEmits(["toSonChild"]);
// 触发自定义事件,并传递参数
const passMessage = () => {
changeFather("toSonChild", "我是子组件传递的数据");
};
</script>
浏览器展示: