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>

更多:组件之间通讯传值

相关推荐
一只大侠的侠21 分钟前
React Native for OpenHarmony:DatePicker 日期选择器组件详解
javascript·react native·react.js
JosieBook25 分钟前
【Vue】15 Vue技术——Vue计算属性简写:提升代码简洁性的高效实践
前端·javascript·vue.js
rfidunion1 小时前
springboot+VUE+部署(11。Nginx)
linux·vue.js·nginx
weixin199701080161 小时前
Lazada商品详情页前端性能优化实战
前端·性能优化
x-cmd1 小时前
[x-cmd] Node.js 的关键一步:原生运行 TypeScript 正式进入 Stable
javascript·typescript·node.js·x-cmd
星火开发设计1 小时前
异常规范与自定义异常类的设计
java·开发语言·前端·c++
CappuccinoRose2 小时前
CSS 语法学习文档(十一)
前端·css·学习·表单控件
海兰2 小时前
Elastic Stack 9.3.0 日志探索
java·服务器·前端
御坂10101号2 小时前
JIT 上的 JIT:Elysia JS 的优化实践与争议
开发语言·javascript·网络·性能优化·node.js·express
一只大侠的侠3 小时前
React Native实战:高性能Popover弹出框组件
javascript·react native·react.js