1:子组件调用父组件
父组件:
<template> <div> <button style="margin: 50px">父按钮</button> <!--已clk为名称的事件传递给子组件,传递的是父组件的a函数/事件 --> <Child @clk="a" /> </div> </template> <script setup> //引用父组件 import Child from "@/components/Child.vue"; const a = () => { console.log(111); }; </script> <style> * { padding: 0; margin: 0; } </style>
子组件:
<template> <div> <!-- 调用子组件的方法去触发父组件传递过来的方法--> <button style="margin: 50px" @click="as">子按钮</button> </div> </template> <script setup> // 接受传递过来的自定义事件名称 :clk // 这里使用的是vue3的defineEmits事件,不知道的可以去官网看下 // 命名为emit主要是为了便于分辨和调用 let emit = defineEmits(["clk"]); // 子组件自身的调用事件以此来触发父组件的事件 const as = () => { // 使用emit传递clk方法,让父组件接收并调用 emit("clk"); }; </script> <style> * { padding: 0; margin: 0; } </style>
效果:
子组件调用父组件
2:父组件调用子组件
父组件:
<template> <div> <button style="margin: 50px" @click="aa">父按钮</button> <!-- 使用ref获取到子组件的信息 --> <Child ref="zi" /> </div> </template> <script setup> import Child from "@/components/Child.vue"; import { ref } from "vue"; // 声明ref来获取子组件信息 const zi = ref(); // 通过ref.value.方法/事件 来调用事件 const aa = () => { zi.value.as(); }; </script> <style> * { padding: 0; margin: 0; } </style>
子组件:
<template> <div> <button style="margin: 50px">子按钮</button> </div> </template> <script setup> // 被父组件调用的方法/事件 const as = () => { console.log(111); }; // 关键处:需要利用defineExpose将事件给暴露出去让父组件进行调用 defineExpose({ as, }); </script> <style> * { padding: 0; margin: 0; } </style>
效果:
父组件调用子组件效果