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>

更多:组件之间通讯传值

相关推荐
GISer_Jing4 分钟前
跨境营销前端AI应用业务领域
前端·人工智能·aigc
oak隔壁找我11 分钟前
Node.js的package.json
前端·javascript
talenteddriver15 分钟前
web: http请求(自用总结)
前端·网络协议·http
全栈派森18 分钟前
Flutter 实战:基于 GetX + Obx 的企业级架构设计指南
前端·flutter
Awu122727 分钟前
Vue3自定义渲染器:原理剖析与实践指南
前端·vue.js·three.js
支撑前端荣耀31 分钟前
从零实现前端监控告警系统:SMTP + Node.js + 个人邮箱 完整免费方案
前端·javascript·面试
进击的野人31 分钟前
Vue.js 插槽机制深度解析:从基础使用到高级应用
前端·vue.js·前端框架
重铸码农荣光34 分钟前
🎯 从零搭建一个 React Todo 应用:父子通信、状态管理与本地持久化全解析!
前端·react.js·架构
用户40993225021235 分钟前
Vue3 v-if与v-show:销毁还是隐藏,如何抉择?
前端·vue.js·后端
Mr_chiu35 分钟前
🚀 效率暴增!Vue.js开发必知的15个神级提效工具
前端