Vue3 父组件如何触发子组件方法 - 两种常用技巧
在 Vue3 中,可以使用 'ref' 和 'teleport' 来触发子组件中的方法。
1. 使用 'ref' 获取子组件实例,然后调用其方法。
在父组件中使用 'ref' 获取子组件实例,然后调用其方法。
<template>
<div>
<ChildComponent ref='childRef' />
<button @click='handleClick'>触发子组件方法</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleClick() {
this.$refs.childRef.childMethod();
}
}
}
</script>
在子组件中,需要使用 'provide' 提供方法,然后在 'inject' 中接收。
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
setup() {
const message = '我是子组件';
const childMethod = () => {
console.log('子组件方法被调用');
}
provide('childMethod', childMethod);
return {
message
}
}
}
</script>
在父组件中使用 'inject' 接收子组件提供的方法。
import { inject } from 'vue';
export default {
setup() {
const childMethod = inject('childMethod');
const handleClick = () => {
childMethod();
}
return {
handleClick
}
}
}
2. 使用 'teleport' 传递事件
在子组件中,使用 'teleport' 将事件传递到父组件。在父组件中监听该事件,然后触发子组件的方法。
<template>
<div>
<ChildComponent @child-method='handleChildMethod' />
<button @click='handleClick'>触发子组件方法</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleClick() {
this.$teleport('child-method', 'hello from parent');
},
handleChildMethod(data) {
console.log(data);
}
}
}
</script>
在子组件中,使用 'emit' 触发父组件传递的事件。
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
setup() {
const message = '我是子组件';
const childMethod = () => {
console.log('子组件方法被调用');
emit('child-method', 'hello from child');
}
return {
message,
childMethod
}
}
}
</script>
原文地址: https://www.cveoy.top/t/topic/nwHc 著作权归作者所有。请勿转载和采集!