vue.js - 使用组合 API 从另一个组件调用函数

标签 vue.js vuejs3 vue-composition-api

下面是标题和正文(不同的组件)的代码。当您在组件 1 中时,如何使用组合 API 方式调用组件 2 的 continue 函数并传递参数...

组件 2:

export default {
    setup() {
        const continue = (parameter1) => {
            // do stuff here
        }
        
        return {
            continue
        }
    }
}

enter image description here

最佳答案

解决这个问题的一种方法是使用事件进行父子通信,并结合模板引用,从中可以直接调用子方法。

  1. 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>
  1. 在父组件中,在 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>
  1. 要链接父级中的两个组件,请使用 v-on directive(或 @ 速记)将 myCompContinue 设置为 ComponentB.vue' s continue-event 的事件处理程序,在步骤 1 中发出:
<template>
  ⋮
  <ComponentB @continue-event="myCompContinue" />
</template>

demo

注意:默认情况下,使用 Options API 编写的组件(如您在问题中使用的那样)会通过模板引用公开其方法和 Prop ,但对于使用 <script setup> 编写的组件而言并非如此。在这种情况下,需要 defineExpose 来公开所需的方法。

关于vue.js - 使用组合 API 从另一个组件调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72223441/

相关文章:

javascript - 从另一个元素实例引用 Vue 实例

firebase - 使用带有 vuefire 手动绑定(bind)的 Firebase 用户 UID

vuejs3 - vue 和 vitest,data-v-[random-number] 属性被添加到 html

vue.js - 为什么我在 Vue.js 3 中使用 async setup() 时得到空白(空)内容?

javascript - 在 Vue.js 3 中,为什么我必须在 ref 上使用 value 属性,而不是在响应式上使用?

javascript - @vue-composition/如何在 setup() 中使用异步方法

vue.js - Ag-Grid 20.1.0 + Vuetify 中的垂直滚动问题

node.js - 如何丑化文件并保存到另一个位置(vue.js)

javascript - 如何在 `name` 中定义 `inheritAttrs` 和 `&lt;script setup>` ?

unit-testing - 你如何在 Jest 测试中访问 Vue-Composition-API 类型 refs & "data"?