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>

更多:组件之间通讯传值

相关推荐
北城笑笑1 分钟前
Vue 99 ,Vue 项目代理配置规范:跨域解决、路径重写与多环境适配最佳实践( 企业级避坑指南 )
运维·前端·nginx·vue
梵得儿SHI3 分钟前
Vue3 实战:从 0 搭建企业级后台管理系统(Router+Pinia+Axios+Element Plus 全整合)
前端·javascript·vue.js·pinia状态管理·项目初始化·页面路由配置·后台首页布局
不能只会打代码4 分钟前
基于Vue 3 + Spring Boot的物联网生鲜品储运系统设计与实现(源码附有详细的文档讲解)
java·前端·vue.js·spring boot·后端·物联网·github
A923A5 分钟前
【Vue3大事件 | 项目笔记】第三天
前端·vue.js·笔记·vue·前端项目
Smoothcloud润云9 分钟前
告别 Selenium:Playwright 现代 Web 自动化测试从入门到实战
前端·人工智能·selenium·测试工具·架构·自动化
前端小D12 分钟前
ES6 中的 Promise
前端·javascript·es6·promise
光影少年13 分钟前
React和Vue的区别?
前端·vue.js·react.js
遗憾随她而去.14 分钟前
前端跨页面通信:8 种方案全解析(附实战案例)
前端
何中应16 分钟前
<el-tag>标签使用
前端·vue.js·elementui
清汤饺子18 分钟前
Cursor 独有的 12 个技巧:这些是 Claude Code 没有的
前端·后端·ai编程