下面是标题和正文(不同的组件)的代码。当您在组件 1 中时,如何使用组合 API 方式调用组件 2 的 continue 函数并传递参数...
组件 2:
export default {
setup() {
const continue = (parameter1) => {
// do stuff here
}
return {
continue
}
}
}
最佳答案
解决这个问题的一种方法是使用事件进行父子通信,并结合模板引用,从中可以直接调用子方法。
- 在
ComponentB.vue
中,发出父级可以收听的事件(例如,命名为continue-event
)。我们使用按钮单击来触发此示例的事件:
<!-- ComponentB.vue -->
<script>
export default {
emits: ['continue-event'],
}
</script>
<template>
<h2>Component B</h2>
<button @click="$emit('continue-event', 'hi')">Trigger continue event</button>
</template>
- 在父组件中,在
ComponentA.vue
上使用 template ref 以在 JavaScript 中获取对它的引用,并创建一个函数(例如,命名为myCompContinue
)以直接调用子组件的continueFn
。
<!-- Parent.vue -->
<script>
import { ref } from 'vue'
export default {
⋮
setup() {
const myComp = ref()
const myCompContinue = () => myComp.value.continueFn('hello from B')
return {
myComp,
myCompContinue,
}
},
}
</script>
<template>
<ComponentA ref="myComp" />
⋮
</template>
- 要链接父级中的两个组件,请使用
v-on
directive(或@
速记)将myCompContinue
设置为ComponentB.vue'
scontinue-event
的事件处理程序,在步骤 1 中发出:
<template>
⋮
<ComponentB @continue-event="myCompContinue" />
</template>
注意:默认情况下,使用 Options API 编写的组件(如您在问题中使用的那样)会通过模板引用公开其方法和 Prop ,但对于使用 <script setup>
编写的组件而言并非如此。在这种情况下,需要 defineExpose
来公开所需的方法。
关于vue.js - 使用组合 API 从另一个组件调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72223441/