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>

更多:组件之间通讯传值

相关推荐
Highcharts.js6 分钟前
玩转Highcharts气泡图|从散点图到气泡图:增加一个维度,数据可视化瞬间立体起来
javascript·信息可视化·散点图·highcharts·图表开发·气泡图·图表创建
A_B_C_Q1 小时前
StringBuilder 与 StringBuffer的区别
java·前端
颜酱1 小时前
差分数组:高效处理数组区间批量更新的核心技巧
javascript·后端·算法
洋洋技术笔记1 小时前
vue3+vite+elementplus简单介绍
前端
Joker Zxc1 小时前
【前端基础(Javascript部分)】2、JavaScript的变量和数据类型
开发语言·前端·javascript
yuki_uix1 小时前
别再死记优缺点了:聊聊 REST、GraphQL、WebSocket 的使用场景
前端
We་ct2 小时前
LeetCode 173. 二叉搜索树迭代器:BSTIterator类 实现与解析
前端·算法·leetcode·typescript
weixin_395448912 小时前
main.c_0222cursor
c语言·前端·算法
无尽的沉默2 小时前
Thymeleaf 表达式
java·开发语言·前端
无尽的沉默2 小时前
Spring Boot 整合 Thymeleaf 模板引擎
java·前端·spring boot