在Vue3中,可以通过ref
来获取子组件实例,然后调用子组件的方法。具体步骤如下:
- 在子组件中,使用
ref
来获取子组件实例:
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
setup() {
const childComponentRef = ref(null)
const triggerChildMethod = () => {
childComponentRef.value.childMethod()
}
return {
childComponentRef,
triggerChildMethod
}
}
}
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
name: 'ChildComponent',
data() {
return {
message: 'Hello from child component!'
}
},
methods: {
childMethod() {
console.log('Child method called!')
}
}
}
</script>
2.在父组件中,使用ref
来获取子组件实例,并定义一个方法来触发子组件的方法:
<template>
<div>
<ChildComponent ref="childComponentRef" />
<button @click="triggerChildMethod">Trigger child method</button>
</div>
</template>
<script>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
setup() {
const childComponentRef = ref(null)
const triggerChildMethod = () => {
childComponentRef.value.childMethod()
}
return {
childComponentRef,
triggerChildMethod
}
}
}
</script>
3。在父组件中,使用ref
来获取子组件实例,并在setup
函数中定义一个方法来触发子组件的方法。然后在模板中绑定一个按钮,当点击按钮时,调用triggerChildMethod
方法来触发子组件的方法:
<template>
<div>
<ChildComponent ref="childComponentRef" />
<button @click="triggerChildMethod">Trigger child method</button>
</div>
</template>
<script>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
setup() {
const childComponentRef = ref(null)
const triggerChildMethod = () => {
childComponentRef.value.childMethod()
}
return {
childComponentRef,
triggerChildMethod
}
}
}
</script>
或者子组件用 defineExpose用法
<script setup>
import { ref } from 'vue';
const demo=ref('测试用例')
const handleVal=()=>{
demo.value="已改变"
}
//将需要暴露出去的数据与方法都可以暴露出去
defineExpose({
demo,
handleVal,
})
</script>
<template>
<div class="inner">
{{demo}}
<button @click="handleVal">改值</button>
</div>
</template>
<style lang="scss" scoped>
</style>