mpa*_*cia 2 vue.js vuejs3 vue-composition-api
下面是标题和正文(不同组件)的代码。当你在组件1内部时,如何使用组合API方式调用组件2的继续函数并传递参数......
第 2 部分:
export default {
setup() {
const continue = (parameter1) => {
// do stuff here
}
return {
continue
}
}
}
Run Code Online (Sandbox Code Playgroud)
解决这个问题的一种方法是使用事件进行父子通信,结合模板引用,可以直接调用子方法。
\nComponentB.vue事件(例如,named )。continue-event在本例中,我们使用按钮单击来触发事件:<!-- ComponentB.vue -->\n<script>\nexport default {\n emits: [\'continue-event\'],\n}\n</script>\n\n<template>\n <h2>Component B</h2>\n <button @click="$emit(\'continue-event\', \'hi\')">Trigger continue event</button>\n</template>\nRun Code Online (Sandbox Code Playgroud)\nComponentA.vue获取 JavaScript 中对其的引用,并创建一个函数(例如,named myCompContinue)来直接调用子组件continueFn。<!-- Parent.vue -->\n<script>\nimport { ref } from \'vue\'\n\nexport default {\n \xe2\x8b\xae\n setup() {\n const myComp = ref()\n const myCompContinue = () => myComp.value.continueFn(\'hello from B\')\n\n return {\n myComp,\n myCompContinue,\n }\n },\n}\n</script>\n\n<template>\n <ComponentA ref="myComp" />\n \xe2\x8b\xae\n</template>\nRun Code Online (Sandbox Code Playgroud)\nv-on指令(或@简写)将其设置为步骤 1 中发出的smyCompContinue的事件处理程序:ComponentB.vue\'continue-event<template>\n \xe2\x8b\xae\n <ComponentB @continue-event="myCompContinue" />\n</template>\nRun Code Online (Sandbox Code Playgroud)\n\n注意:使用 Options API 编写的组件(正如您在问题中使用的那样)默认情况下通过模板引用公开其方法和属性,但对于使用<script setup>. 在这种情况下,defineExpose需要公开所需的方法。
这是我使用脚本设置语法解决它的方法:
家长:
<script setup>
import { ref } from 'vue';
const childComponent = ref(null);
const onSave = () => {
childComponent.value.saveThing();
};
</script>
<template>
<div>
<ChildComponent ref="childComponent" />
<SomeOtherComponent
@save-thing="onSave"
/>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
子组件:
<script setup>
const saveThing = () => {
// do stuff
};
defineExpose({
saveThing,
});
</script>
Run Code Online (Sandbox Code Playgroud)
没有 就无法工作defineExpose。除此之外,唯一的技巧是在您尝试调用函数的组件上创建引用。
在上面的代码中, do 不起作用@save-thing="childComponent.saveThing",原因似乎是组件最初安装时 ref 为空。
| 归档时间: |
|
| 查看次数: |
9349 次 |
| 最近记录: |