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>

更多:组件之间通讯传值

相关推荐
灵感__idea5 小时前
Hello 算法:让前端人真正理解算法
前端·javascript·算法
向葭奔赴♡6 小时前
CSS是什么?—— 网页的“化妆师”
前端·css
黑犬mo6 小时前
在Edge、Chrome浏览器上安装uBlock Origin插件
前端·edge
excel6 小时前
🧩 Vue 3 watch 源码详解(含完整注释)
前端·javascript·vue.js
大前端helloworld6 小时前
前端梳理体系从常问问题去完善-网络篇
前端·面试
excel6 小时前
🌿 一文看懂 Vue 3 的 watch 源码:从原理到流程
前端
繁依Fanyi7 小时前
让工具说话:我在 Inspira Board 里用 AI 把“能用、好用、可复用”落成了日常
前端
weixin_456904278 小时前
C# 中的回调函数
java·前端·c#
kura_tsuki8 小时前
[Web网页] LAMP 架构与环境搭建
前端·架构
yinuo8 小时前
UniApp+Vue3多分包引入同一 npm 库被重复打包至 vendor 的问题分析与解决
前端