父组件向子组件通信
<template>
<div class="container">
<childComponent :msg="msg">childComponent>
div>
template>
<script setup>
import { ref } from 'vue';
import childComponent from '../components/childComponent.vue'
const msg = ref("父组件传给子组件的值");
script>
<template>
<div class="container">
<div>{{ msgValue }}div>
div>
template>
<script setup>
import { ref } from "vue"
const msgValue = ref(null)
const props = defineProps({
msg: {
type: String,
default: ""
}
})
msgValue.value = props.msg
script>
子组件向父组件通信
<template>
<div class="container">
<span>{{ childVlaue }}span>
<childComponent @myClick="onMyClick">childComponent>
div>
template>
<script setup>
import { ref } from 'vue'
import childComponent from '../components/childComponent.vue'
const childVlaue = ref(null)
const onMyClick = (val) => {
childVlaue.value = val
}
script>
<template>
<div class="container">
<el-button type="primary" size="default" @click="handleClick">子组件向父组件通信el-button>
div>
template>
<script setup>
const emit = defineEmits(["handleClick"]);
const handleClick = () => {
// 触发父组件中的方法,并把值以参数的形式传过去
// 这里触发的方法名要和父组件中@符后面的名称一样
emit("myClick", "子组件向父组件传送的信息");
}
script>