vue3父组件通过ref调用子组件的方法(组合模式,defineExpose)_人工智能

 

Index.vue:

<script setup>
import { ref, onMounted } from 'vue'
import Child from './Child.vue'
import './index.css'

const child = ref(null)

onMounted(() => {
  child.value.handleGetValue()
})
</script>

<template>
  <div class="m-home-wrap">
    <Child ref="child"></Child>
    <div class="m-home-demo"></div>
  </div>
</template>

<style></style>

Child.vue:

<template>
  <div>child</div>
</template>

<script setup>
const handleGetValue = () => {
  console.log('子组件的方法')
}

defineExpose({
  handleGetValue
})
</script>

<style></style>