Vue3 子/父组件相互调用

简介: Vue3 子/父组件相互调用

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>

效果:

父组件调用子组件效果

相关文章
|
4天前
|
JavaScript 前端开发 CDN
vue3速览
vue3速览
14 0
|
4天前
|
设计模式 JavaScript 前端开发
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
|
4天前
|
JavaScript API
Vue3 官方文档速通(中)
Vue3 官方文档速通(中)
20 0
|
4天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(上)
Vue3 官方文档速通(上)
26 0
|
4天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
8 1
|
4天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
10 0
|
4天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
8 0
|
4天前
|
JavaScript 前端开发 API
Vue3 系列:从0开始学习vue3.0
Vue3 系列:从0开始学习vue3.0
10 1
|
4天前
|
网络架构
Vue3 系列:vue-router
Vue3 系列:vue-router
9 2
|
4天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
9 1