Thursday, May 20, 2021

Call a child component method from a parent in vuejs

Answer # 1

For small things, you can also call child component methods with $refs likethis. $refs.foo.bar ().
However, direct data reference between components is not recommended.

Component-Vue.js

  

However, it is also very important to keep the parent and child as separated as possible through a well-defined interface. This ensures that the code for each component is written and judged relatively independently. Therefore, components can be made more maintainable and potentially reusable

So basically

$emit from child to parent

Parent to child props

It may be good to pass data with

.

However, props cannot directly call child component methods.
Therefore, there is a way to use EventBus as shown below to coordinate processing between components.

Communication other than parent-child

  1. var EventBus = new Vue ()
  2. Object.defineProperties (Vue.prototype, {
  3.     $bus: {
  4.         get () {
  5.             return EventBus
  6.         }
  7.     }
  8. }
  9. let ComponentY = Vue.extend ({
  10.   mounted () {
  11.     this. $bus. $on ('onMountedX', () =>{
  12.         console.log ('onMountedX')
  13.     })
  14.   }
  15. })
  16. let ComponentX = Vue.extend ({
  17.   mounted () {
  18.     this. $bus. $emit ('onMountedX')
  19.   }
  20.   components: [ComponentY]
  21. })
Answer # 2

Looks good with ref

Use vuex for more complex


Answer # 3

If you allow child components to be referenced with the ref attribute, you can call child methods from the parent
The following is a sample program.
The test method of the parent component App.vue calls the method of the child component Test.vue using $refs.

App.vue

  1. <template>
  2.   <div id = "app">
  3.     <test ref = "test"></test>
  4.     <button @ click = "test">test</button>
  5.   </div>
  6. </template>
  7. <script>
  8. import Test from "./Test.vue"
  9. export default {
  10.   methods: {
  11.     test () {
  12.       console.log ("parentMethod")
  13.       this. $refs.test.childMethod ()
  14.     },
  15.   },
  16.   components: {Test}
  17. }
  18. </script>