关于vue3:vue3-复合式写法之ref另外的用法获取节点父组件调用子组件方法

6次阅读

共计 622 个字符,预计需要花费 2 分钟才能阅读完成。

应用 ref 来获取节点信息

<template>
    <div ref="DOM">xx</div>
</template>

<script setup>
/*
 
*/
import {ref} from 'vue'
const DOM = ref(null)
console.log(DOM) // <div/>xx</div>
</script>

应用 ref 进行父组件调用子组件办法

网上一些博客间接应用 ref 调用是不能够的,须要应用 vue3 的 API defineExpose 办法将子组件的属性办法和须要裸露进去的属性放进去才能够调用

父组件

<template>
    <childComponent ref="DOM" />
    <button @click="handleClick">click to handle child event</button>
</template>

<script setup>

import {ref} from 'vue'
const DOM = ref(null)

function handleClick() {DOM.value.childClickEvent()
}
</script>

子组件

<template>
    <div>child component</div>
</template>
<script setup>
import {defineExpose} from 'vue'

function chlidClickEvent() {//}
defineExpose({childClickEvent})

</script>
正文完
 0