【问题标题】:Call a function from another component using composition API使用组合 API 从另一个组件调用函数
【发布时间】:2022-08-13 01:42:32
【问题描述】:

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

组件 2:

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

  • 您可以在组件中使用this.$parent 来访问它的父实例
  • @power-cut 你可以,但你不应该。在 AngularJS 中这是一个不好的做法,$parent 来自于 Vue
  • @EstusFlask 我完全同意。但没有什么是无缘无故的存在。有很多方法可以实现相同的目标。

标签: vue.js vuejs3 vue-composition-api


【解决方案1】:

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

  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 编写的组件(正如您在问题中使用的那样)通过模板引用公开其方法和道具,但对于使用 &lt;script setup&gt; 编写的组件而言,情况并非如此。在这种情况下,需要defineExpose 来公开所需的方法。

【讨论】:

    【解决方案2】:

    这是我使用脚本设置语法解决它的方法:

    家长:

    <script setup>
    import { ref } from 'vue';
    
    const childComponent = ref(null);
    
    const handleSave = () => {
        childComponent.value.saveThing();
    };
    </script>
    
    <template>
        <div>
            <ChildComponent ref="childComponent" />
    
            <SomeOtherComponent
                @save-thing="handleSave"
            />
        </div>
    </template>
    

    子组件:

    <script setup>
    const saveThing = () => {
        // do stuff
    };
    
    defineExpose({
        saveThing,
    });
    </script>
    

    如果没有defineExpose,它将无法工作。除此之外,唯一的技巧是在您尝试调用函数的组件上创建一个 ref。

    在上面的代码中,@save-thing="childComponent.saveThing" 是行不通的,看来原因是组件最初挂载时 ref 为空。

    【讨论】:

      猜你喜欢
      • 2017-07-13
      • 2017-01-09
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 2019-02-06
      • 1970-01-01
      相关资源
      最近更新 更多