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>

更多:组件之间通讯传值

相关推荐
朱昆鹏7 分钟前
开源 Claude Code + Codex + 面板 的未来vibecoding平台
前端·后端·github
lyrieek12 分钟前
pgadmin的导出图实现,还在搞先美容后拍照再恢复?
前端
小书包酱14 分钟前
在 VS Code中,vue2-vuex 使用终于有体验感增强的插件了。
vue.js·vuex
永远是我的最爱17 分钟前
基于.NET的小小便利店前台收银系统
前端·sqlserver·.net·visual studio
从文处安18 分钟前
「九九八十一难」第一难:前端数据mock指南(TS + VUE)
前端
Zhencode38 分钟前
Vue3 响应式依赖收集与更新之effect
前端·vue.js
x-cmd42 分钟前
[x-cmd] jsoup 1.22.1 版本发布,引入 re2j 引擎,让 HTML 解析更安全高效
前端·安全·html·x-cmd·jsoup
天下代码客1 小时前
使用electronc框架调用dll动态链接库流程和避坑
前端·javascript·vue.js·electron·node.js
weixin199701080161 小时前
【性能提升300%】仿1688首页的Webpack优化全记录
前端·webpack·node.js
冰暮流星2 小时前
javascript之数组
java·前端·javascript