Vue best practice for calling a method in a child componentCall a Vue.js component method from outside the componentDelete a Vue child componentUpdate parent model from child component Vueduplicate webpack (2.2.0) chunks with vue-componentsVue.js - How to properly watch for nested dataListen to events from parent component in child and execute child’s method in vue without hubVue - Passing slot to child componentVue - closing dialog from child componentFramework 7 Vue - Run Parent Vue's Methods not workingVueJS: Passing child method to parent doesn't execute

How to draw pentagram-like shape in Latex?

Does a windmilling propeller create more drag than a stopped propeller in an engine out scenario

What's is the easiest way to purchase a stock and hold it

How to laser-level close to a surface

Why is choosing a suitable thermodynamic potential important?

Parse a C++14 integer literal

Does the usage of mathematical symbols work differently in books than in theses?

Largest memory peripheral for Sinclair ZX81?

Shortest amud or daf in Shas?

Failing students when it might cause them economic ruin

What do you call bracelets you wear around the legs?

Lock out of Oracle based on Windows username

Why didn't Daenerys' advisers suggest assassinating Cersei?

Should all adjustments be random effects in a mixed linear effect?

Why do academics prefer Mac/Linux?

French equivalent of the German expression "flöten gehen"

In Dutch history two people are referred to as "William III"; are there any more cases where this happens?

How can sister protect herself from impulse purchases with a credit card?

Can more than one instance of Bend Luck be applied to the same roll by multiple Wild Magic sorcerers?

Told to apply for UK visa before other visas, on UK-Spain-etc. visit

Is my homebrew Awakened Bear race balanced?

Why does string strummed with finger sound different from the one strummed with pick?

How to scale and shift the coordinates of a Graphics object?

Was Tyrion always a poor strategist?



Vue best practice for calling a method in a child component


Call a Vue.js component method from outside the componentDelete a Vue child componentUpdate parent model from child component Vueduplicate webpack (2.2.0) chunks with vue-componentsVue.js - How to properly watch for nested dataListen to events from parent component in child and execute child’s method in vue without hubVue - Passing slot to child componentVue - closing dialog from child componentFramework 7 Vue - Run Parent Vue's Methods not workingVueJS: Passing child method to parent doesn't execute






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















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!










share|improve this question






















  • Also, Vue docs suggests that 'props' are the best way to achieve this. I know that the Vue docs are much praised, and they certainly are good. Just wish they had some real simple examples for idiots like me sometimes. Thanks

    – user1525612
    Mar 23 at 17:33

















1















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!










share|improve this question






















  • Also, Vue docs suggests that 'props' are the best way to achieve this. I know that the Vue docs are much praised, and they certainly are good. Just wish they had some real simple examples for idiots like me sometimes. Thanks

    – user1525612
    Mar 23 at 17:33













1












1








1








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!










share|improve this question














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!







vue.js






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 23 at 17:29









user1525612user1525612

557419




557419












  • Also, Vue docs suggests that 'props' are the best way to achieve this. I know that the Vue docs are much praised, and they certainly are good. Just wish they had some real simple examples for idiots like me sometimes. Thanks

    – user1525612
    Mar 23 at 17:33

















  • Also, Vue docs suggests that 'props' are the best way to achieve this. I know that the Vue docs are much praised, and they certainly are good. Just wish they had some real simple examples for idiots like me sometimes. Thanks

    – user1525612
    Mar 23 at 17:33
















Also, Vue docs suggests that 'props' are the best way to achieve this. I know that the Vue docs are much praised, and they certainly are good. Just wish they had some real simple examples for idiots like me sometimes. Thanks

– user1525612
Mar 23 at 17:33





Also, Vue docs suggests that 'props' are the best way to achieve this. I know that the Vue docs are much praised, and they certainly are good. Just wish they had some real simple examples for idiots like me sometimes. Thanks

– user1525612
Mar 23 at 17:33












3 Answers
3






active

oldest

votes


















2














You can create a ref and access the methods, but this is not recommended. You should'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 parent communicate with children via props and children communicate with parent 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)






share|improve this answer























  • Hi Radu, thanks for the great and clear explanation and steps. Your solution works well and I like that it conforms to the 'contract'!

    – user1525612
    Mar 23 at 22:02


















2














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.






share|improve this answer






























    1














    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>





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55316490%2fvue-best-practice-for-calling-a-method-in-a-child-component%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      You can create a ref and access the methods, but this is not recommended. You should'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 parent communicate with children via props and children communicate with parent 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)






      share|improve this answer























      • Hi Radu, thanks for the great and clear explanation and steps. Your solution works well and I like that it conforms to the 'contract'!

        – user1525612
        Mar 23 at 22:02















      2














      You can create a ref and access the methods, but this is not recommended. You should'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 parent communicate with children via props and children communicate with parent 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)






      share|improve this answer























      • Hi Radu, thanks for the great and clear explanation and steps. Your solution works well and I like that it conforms to the 'contract'!

        – user1525612
        Mar 23 at 22:02













      2












      2








      2







      You can create a ref and access the methods, but this is not recommended. You should'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 parent communicate with children via props and children communicate with parent 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)






      share|improve this answer













      You can create a ref and access the methods, but this is not recommended. You should'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 parent communicate with children via props and children communicate with parent 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)







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Mar 23 at 20:42









      Radu DițăRadu Diță

      4,38311321




      4,38311321












      • Hi Radu, thanks for the great and clear explanation and steps. Your solution works well and I like that it conforms to the 'contract'!

        – user1525612
        Mar 23 at 22:02

















      • Hi Radu, thanks for the great and clear explanation and steps. Your solution works well and I like that it conforms to the 'contract'!

        – user1525612
        Mar 23 at 22:02
















      Hi Radu, thanks for the great and clear explanation and steps. Your solution works well and I like that it conforms to the 'contract'!

      – user1525612
      Mar 23 at 22:02





      Hi Radu, thanks for the great and clear explanation and steps. Your solution works well and I like that it conforms to the 'contract'!

      – user1525612
      Mar 23 at 22:02













      2














      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.






      share|improve this answer



























        2














        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.






        share|improve this answer

























          2












          2








          2







          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.






          share|improve this answer













          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.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 23 at 19:01









          FlameFlame

          1,092820




          1,092820





















              1














              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>





              share|improve this answer



























                1














                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>





                share|improve this answer

























                  1












                  1








                  1







                  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>





                  share|improve this answer













                  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>






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 23 at 18:21









                  dagaltidagalti

                  752137




                  752137



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55316490%2fvue-best-practice-for-calling-a-method-in-a-child-component%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현