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里面引入;直接使用即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM