组件通信
父子通信
子组件
<template>
<h1>{{ name }}- 子组件的属性</h1>
<button @click="send">发送数据给父组件</button>
</template>
<script setup>
import { ref } from "vue";
// 方法一 获取父组件传参
defineProps({
name: String,
});
// 方法二 获取父组件传参
const props = defineProps(['name'])
let name = ref(props.name)
console.log(name)
// defineEmits 接收与 emits 选项相同的值
const emit = defineEmits(['sub'])
let send = () => {
emit("sub", "hello son2");
};
</script>
父组件
<template>
<son1 :name="name" @sub="GetData">son1组件</son1>
</template>
<script setup>
// 引入响应式数据对象 = data
import { ref } from 'vue'
// 子组件引入
import son1 from './demo2.vue'
//初始化一个响应式数据
let name = ref('hello world')
let GetData = (data) =>
{
// 子组件传过来的参数
console.log(data)
}
</script>