user1525612
user1525612

Reputation: 2014

Vue best practice for calling a method in a child component

I have been reading lots of articles about this, and it seems that there are multiple ways to do this with many authors advising against some implementations.

To make this simple I have created a really simple version of what I would like to achieve.

I have a parent Vue, parent.vue. It has a button:

<template>
    <div>
        <button v-on:click="XXXXX call method in child XXXX">Say Hello</button>
    </div>
</template>

In the child Vue, child.vue I have a method with a function:

methods: {
    sayHello() {

        alert('hello');
   }
  }

I would like to call the sayHello() function when I click the button in the parent.

I am looking for the best practice way to do this. Suggestions I have seen include Event Bus, and Child Component Refs and props, etc.

What would be the simplest way to just execute the function in my method?

Apologies, this does seem extremely simple, but I have really tried to do some research.

Thanks!

Upvotes: 109

Views: 127205

Answers (9)

Theodore MCA
Theodore MCA

Reputation: 1178

Clear example with Vue 3 ts Setup script

// Child

<template>
  <button @click="doSomething">doSomething</button>
</template>
<script setup lang="ts">
  const doSomething() {}
  defineExpose({
    doSomething
  })
</script>

// Parent

<template>
  <child-component ref="childComponentRef" />
  <button @click="triggerDoSomething">Trigger Child's Action</button>
</template>
<script setup lang="ts">
import { ref } from "vue";
import ChildComponent from "./ChildComponent.vue";
 const childComponentRef = ref(null);
 
 const triggerDoSomething = () => {
     if (childComponentRef.value) {
         (childComponentRef.value as { doSomething: () => void }).doSomething();
     }
 };
</script>

Upvotes: 2

Darkproduct
Darkproduct

Reputation: 1243

Creating a property and a watcher in the child element is overly complicated. I liked Flame's answer the most, but I had a lot if trouble getting it to work in typescript with type information and the options API. If you want to read more, look at this answer.

Here is the solution for Vue 3 + Typescript + Options API with type information:

// 2023-05-21
Vue        3.3.4
Typescript 5.0.4
Vite       4.3.8

In the child:

export default {
  expose: ['childMethod'],
  methods: {
    childMethod() {
      /* ... */
    },
  }
}

Using expose is not necessary, but I like it.

In the parent:

  • Add a ref to the child component
<ChildComponent ref="childComponent"></ChildComponent>
  • A wrapper function
methods: {
  callChildMethod() {
    (this.$refs.childComponent as typeof ChildComponent).childMethod();
  },
}
  • and finally you can call the method from an event
<something v-on:click="callChildMethod()"></something>

You unfortunately can not directly do this

<something v-on:click="($refs.childComponent as typeof ChildComponent).childMethod()"></something>

Upvotes: 3

MrSpt
MrSpt

Reputation: 1073

With vue 3 composition api you can use defineExpose. More information can be found here

Parent.vue

<script setup lang="ts">
const childRef = ref()

const callSayHello = () => {
  childRef.value.sayHello()
}
</script>

<template>
  <child ref="childRef"></child>
</template>

<style scoped></style>

Child.vue

<script setup lang="ts">
const sayHello = () => {
  console.log('Hello')
}
defineExpose({ sayHello })
</script>

<template></template>

<style scoped></style>

Upvotes: 41

Souf
Souf

Reputation: 345

if you're using <script setup> you should be aware that your component is closed by default. Meaning everything is private and you won't be able to access properties or methods outside the component UNLESS You use defineExpose() to expose properties/methods you need. Here's an example:

<script setup>
import { ref } from 'vue'

const a = 1
const b = ref(2)

defineExpose({
  a,
  b
})
</script>

Here's a reference to vue's documentation

Upvotes: 3

Dirigible
Dirigible

Reputation: 1968

This is an alternate take on Jonas M's excellent answer. Return the interface with a promise, no need for events. You will need a Deferred class.

IMO Vue is deficient in making calling child methods difficult. Refs aren't always a good option - in my case I need to call a method in one of a thousand grandchildren.

Parent

    <child :getInterface="getInterface" />
    ...
    
    export default {
        setup(props) {
            init();
        }
        async function init() {
            ...
            state.getInterface = new Deferred();
            state.childInterface = await state.getInterface.promise;
            state.childInterface.doThing();
        }
    }

Child

    export default {
        props: {
            getInterface: Deferred,
        },
        setup(props) {
            watch(() => props.getInterface, () => {
                if(!props.getInterface) return;
                props.getInterface.resolve({
                    doThing: () => {},
                    doThing2: () => {},
                });
            });
        }
    }

Upvotes: 1

Jonas m
Jonas m

Reputation: 2734

I don't like the look of using props as triggers, but using ref also seems as an anti-pattern and is generally not recommended.

Another approach might be: You can use events to expose an interface of methods to call on the child component this way you get the best of both worlds while keeping your code somehow clean. Just emit them at the mounting stage and use them when pleased. I stored it in the $options part in the below code, but you can do as pleased.

Child component

<template>
  <div>
    <p>I was called {{ count }} times.</p>
  </div>
</template>
<script>
  export default {
    mounted() {
      // Emits on mount
      this.emitInterface();
    },
    data() {
      return {
        count: 0
      }
    },
    methods: {

      addCount() {
        this.count++;
      },

      notCallable() {
        this.count--;
      },

      /**
       * Emitting an interface with callable methods from outside
       */
      emitInterface() {
        this.$emit("interface", {
          addCount: () => this.addCount()
        });
      }

    }
  }
</script>

Parent component

<template>
  <div>
    <button v-on:click="addCount">Add count to child</button>
    <child-component @interface="getChildInterface"></child-component>
  </div>
</template>
<script>
  export default {
    // Add a default
    childInterface: {
      addCount: () => {}
    },

    methods: {
      // Setting the interface when emitted from child
      getChildInterface(childInterface) {
        this.$options.childInterface = childInterface;
      },

      // Add count through the interface
      addCount() {
        this.$options.childInterface.addCount();
      }
    }
  }
</script>

Upvotes: 44

Radu Diță
Radu Diță

Reputation: 14191

You can create a ref and access the methods, but this is not recommended. You shouldn't rely on the internal structure of a component. The reason for this is that you'll tightly couple your components and one of the main reasons to create components is to loosely couple them.

You should rely on the contract (interface in some frameworks/languages) to achieve this. The contract in Vue relies on the fact that parents communicate with children via props and children communicate with parents via events.

There are also at least 2 other methods to communicate when you want to communicate between components that aren't parent/child:

  • the event bus
  • vuex

I'll describe now how to use a prop:

  1. Define it on your child component

    props: ['testProp'],
    methods: {
      sayHello() {
        alert('hello');
      }
    }
    
  2. Define a trigger data on the parent component

    data () {
     return {
       trigger: 0
     }
    }
    
  3. Use the prop on the parent component

    <template>
     <div>
        <childComponent :testProp="trigger"/>
      </div>
    </template>
    
  4. Watch testProp in the child component and call sayHello

    watch: { 
        testProp: function(newVal, oldVal) {
          this.sayHello()
        }
    }
    
  5. Update trigger from the parent component. Make sure that you always change the value of trigger, otherwise the watch won't fire. One way of doing this is to increment trigger, or toggle it from a truthy value to a falsy one (this.trigger = !this.trigger)

Upvotes: 44

Flame
Flame

Reputation: 7628

One easy way is to do this:

<!-- parent.vue -->
<template>
    <button @click="$refs.myChild.sayHello()">Click me</button>
    <child-component ref="myChild" />
</template>

Simply create a ref for the child component, and you will be able to call the methods, and access all the data it has.

Upvotes: 187

dagalti
dagalti

Reputation: 1956

I am not sure is this the best way. But I can explain what I can do... Codesandbox Demo : https://codesandbox.io/s/q4xn40935w

From parent component, send a prop data lets say msg. Have a button at parent whenever click the button toggle msg true/false

<template>
  <div class="parent">
    Button from Parent : 
    <button @click="msg = !msg">Say Hello</button><br/>
    <child :msg="msg"/>
  </div>
</template>

<script>
import child from "@/components/child";

export default {
  name: "parent",
  components: { child },
  data: () => ({
    msg: false
  })
};
</script>

In child component watch prop data msg. Whenever msg changes trigger a method.

 <template>
  <div class="child">I am Child Component</div>
</template>

<script>
export default {
  name: "child",
  props: ["msg"],
  watch: {
    msg() {
      this.sayHello();
    }
  },
  methods: {
    sayHello() {
      alert("hello");
    }
  }
};
</script>

Upvotes: 3

Related Questions