在我们项目的开发过程中可能需要一个文件的属性能够在另一个页面上做一些操作,但是<script setup>中的属性只能在当前文件中使用,学过java的就知道它类似java文件中用private修改的属性,在java文件中如果想要让属性能够给其他java文件使用的话可以通过为其设定get、set方法,或者改成public修饰符修饰的属性,那么在vue文件中我们也可以通过defineExpose方法来暴露当前vue文件中的变量。
语法:defineExpose({被调用的暴露名字:要暴露出去的变量or方法})
使用案例
暴露一个常量
自定义组件代码
<template>
<view class="box">子组件num值:{{num}}</view>
</template>
<script setup>
import {ref} from "vue";
const num=ref(100);
defineExpose({
//如果暴露出去的名字和要暴露出去的值的名字一样的话可以简写,直接写一个名字即可
num
})
</script>
<style lang="less">
.box{
width: 200px;
height: 200px;
background: darkgray;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
</style>
调用子组件代码
<template>
<view class="">
<test-child-defineExpose ref="child"></test-child-defineExpose>
</view>
</template>
<script setup>
import {onMounted, ref} from "vue";
const child=ref(null);
onMounted(()=>{
console.log(child.value)
})
</script>
<style lang="scss" scoped>
</style>
注意:这里要拿到子组件暴露出来的值的时,需要用挂载后的回调函数来获取,并且,在调用的子组件上用ref来声明一个名字用来获取
页面效果
暴露方法
自定义组件内代码
<template>
<view class="layout">
<view class="box">子组件num值:{{num}}</view>
</view>
</template>
<script setup>
import {ref} from "vue";
const num=ref(100);
const onClickChange= function (){
num.value++;
}
defineExpose({
num,onClickChange
})
</script>
<style lang="less">
.layout{
width: 100%;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
.box{
width: 200px;
height: 200px;
background: dimgray;
text-align: center;
line-height: 200px;
color: white;
}
}
</style>
调用自定义子组件文件内代码
<template>
<view class="">
<test-child-defineExpose ref="child"></test-child-defineExpose>
<button @click="onClick">点击修改子组件num值</button>
</view>
</template>
<script setup>
import {onMounted, ref} from "vue";
const child=ref(null);
function onClick(){
child.value.onClickChange();
}
onMounted(()=>{
console.log(child.value)
})
</script>
<style lang="scss" scoped>
</style>
这里没有在挂载回调函数内调用onClickChange()方法是因为,我们在调用这个方法时,子组件已经被挂载了,就不需要再挂载回调函数中去调用子组件暴露的方法了
页面效果
视频
defineExpose暴露方法演示