在 vue 中调用组件方法的方法有三种:直接调用、通过事件触发和通过 provide/inject 机制。直接调用使用 $refs 对象,通过事件触发使用 @event=”method”,而通过 provide/inject 机制使用 provide() 和 inject()。

如何在 Vue 中调用组件方法
直接调用
要直接调用一个组件方法,请使用 $refs 对象:
// 父组件
<template><childcomponent ref="child"></childcomponent></template><script>
export default {
methods: {
callChildMethod() {
this.$refs.child.childMethod(); // 直接调用子组件中的 childMethod 方法
}
}
}
</script>
登录后复制
通过事件触发
另一种调用组件方法的方法是通过事件触发:
// 父组件
<template><childcomponent></childcomponent></template><script>
export default {
methods: {
callChildMethod(payload) {
// 接收 childMethod 方法传递的 payload
}
}
}
</script>
登录后复制
// 子组件
<template><button>触发方法</button>
</template><script>
export default {
methods: {
childMethod() {
this.$emit('trigger-method', { payload: '数据' }); // 发送事件触发父组件中的方法
}
}
}
</script>
登录后复制
通过 provide/inject
对于需要跨多个组件层级调用的方法,可以使用 provide/inject 机制:
// 父组件
<template><childcomponent></childcomponent></template><script>
export default {
provide() {
return {
callChildMethod: this.callChildMethod
}
},
methods: {
callChildMethod() {
// ...
}
}
}
</script>
登录后复制
// 子组件
<template><grandchildcomponent></grandchildcomponent></template><script>
export default {
inject: ['callChildMethod'],
methods: {
callParentMethod() {
this.callChildMethod(); // 通过 provide 注入的方法调用父组件中的方法
}
}
}
</script>
登录后复制
以上就是vue怎么调用组件方法的详细内容,更多请关注叮当号网其它相关文章!
文章来自互联网,只做分享使用。发布者:代号邱小姐,转转请注明出处:https://www.dingdanghao.com/article/505636.html
