vue3 父组件调用子组件 方法和属性

vue2中调用子组件方法是

this.$refs.child.show();

vue3.2版本就需要子组件defineExpose暴露出方法,其他组件才可以使用

 

父组件app.vue
<script setup>
import { ref } from 'vue'
import Comp from './Comp.vue'
const showComp=ref(null)//这个时候获取了子组件Comp
const childShow=()=>{
  showComp.value.show()//调用子组件的show方法
}
</script>
<template>
<button @click='childShow'>点击调用子组件方法</button>
<Comp ref='showComp'></Comp>
</template>


子组件Comp.vue
<script setup>
import { ref } from 'vue'
const show=()=>{
  alert("我是子组件,我的show方法被调用了")
}
// 主动暴露childMethod方法
defineExpose({ show })
</script>
<template>
<div>我是子组件</div>
</template>

defineExpose是暴露方法的函数,这个函数不需要从vue里面引入;直接使用即可

posted @ 2022-03-18 19:35  青幽草  阅读(3096)  评论(0编辑  收藏  举报