vue3第二十一节(新增编译宏defineExpose)

引言 :在vue2中我们可以使用 this.$refs.xxx调用组件内部的属性或者方法,同时子组件也可以使用 this.$parent.xxx 调用父组件的属性和方法;

但是

当我们在setup 语法糖中,因为此时的组件默认是关闭即组件是私有的 ,故使用$parent.xxx 或者 $children.xxx无法获取到对应的实例 的; 需要链式调用时候,比如父组件需要调用子组件的属性方法,

那么此时我们可以使用defineExpose()来暴露组件的属性方法

父组件:

c 复制代码
<template>
<div>
  defineExpose parent 
  <div>{{msg}}</div>
  <el-button type="primary" @click="changMsg">父组件调用子组件方法</el-button>
  <hr>
  <ExposeChild ref="child" @changemsg="changMsg"></ExposeChild>
</div>
</template>
<script setup>
import { ref } from 'vue'
import ExposeChild from './components/exposeChild.vue'
// 这里ref() 创建的对象要与模板中 ref='name' 的name 保持一致,不然无法读取 子组件
const child = ref(null)
const msg = ref('Andy')
const changMsg = () => {
  // 直接通过ref调用 子组件的方法,前提是已经使用defineExpose() 将方法暴露出来
  child.value.handleChangeName()
  console.log('==child=', child.value)
}
</script>

子组件:

c 复制代码
<template>
<div>
  defineExpose 子组件
  name---{{name}}
  <el-button type="primary" @click="handleChangemsg">子组件调用父组件方法</el-button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const emits = defineEmits(['changemsg'])
const name = ref('Expose')
const handleChangeName = () => {
  name.value = name.value + '' +'ExposeChange'
}
const handleChangemsg = () => {
  emits('changemsg')
}
// 不用引入可以直接使用
defineExpose({
  name, // 暴露出去的属性
  handleChangeName // 暴露出方法
})
</script>

更多:组件之间通讯传值

相关推荐
什么时候吃饭5 分钟前
vue2、vue3父子组件嵌套生命周期执行顺序
前端·vue.js
2501_940943916 分钟前
体系课\ Python Web全栈工程师
开发语言·前端·python
q***06476 分钟前
SpringSecurity相关jar包的介绍
android·前端·后端
低保和光头哪个先来12 分钟前
场景2:Vue Router 中 query 与 params 的区别
前端·javascript·vue.js·前端框架
q***952226 分钟前
SpringMVC 请求参数接收
前端·javascript·算法
|晴 天|27 分钟前
Vite 为何能取代 Webpack?新一代构建工具的崛起
前端·webpack·node.js
带只拖鞋去流浪32 分钟前
迎接2026,重新认识Webpack5
前端·webpack
HIT_Weston1 小时前
43、【Ubuntu】【Gitlab】拉出内网 Web 服务:静态&动态服务
前端·ubuntu·gitlab
LucidX1 小时前
Web——反向代理、负载均衡与 Tomcat 实战部署
前端·tomcat·负载均衡
hhcccchh1 小时前
学习vue第七天 从单页面应用(SPA)进化为后台管理系统架构
vue.js·学习·系统架构