2
I have the following code:
Vue.component('child-comp', {
  template: '<p>Child here</p>',
  props: ['item'],
  methods: {
     alt: function(msg) {
    	alert(msg);
     }
  }
});
new Vue({
  el: '#app',
  data() {
     return {
        item: null
     }
  },
  methods: {
     load_child: function() {
        this.item = true;
        this.$refs['comp1'].alt(this.item.toString());
     }
  }
});<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
  <button v-on:click="load_child">execute child</button>
  <child-comp v-bind:item="item" v-if="item != null" ref="comp1"></child-comp>
</div>As you can see at the first click gives error, saying:
Cannot read Property 'alt' of Undefined / Typeerror: this. $refs.comp1 is Undefined
When starting from the previous line this component (this.item = true;) should already exist/be defined
To get around it I did:
Vue.component('child-comp', {
  template: '<p>Child here</p>',
  props: ['item'],
  methods: {
     alt: function(msg) {
    	alert(msg);
     }
  }
});
new Vue({
  el: '#app',
  data() {
    return {
        item: null
    }
  },
  methods: {
     load_child: function() {
        this.item = true;
        setTimeout(() => {this.$refs['comp1'].alt(this.item.toString());}, 100);
     }
  }
});<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
  <button v-on:click="load_child">execute child</button>
  <child-comp v-bind:item="item" v-if="item != null" ref="comp1"></child-comp>
</div>But I don’t want it and it doesn’t seem right at all.
I’m looking for an alternative to this, did I implement something wrong, or should have done something I didn’t do/know there is.
It wouldn’t be enough to run
this.alt()within themountedofchild-comp?– Sergio
Yes @Sergio , in this case I put yes, but in the project I’m doing there will be arguments to get into "
alt()", which are dynamic and vary according to the parent component– Hula Hula
I still think you should wear
props. Being dependent on asynchrony can cause problems. Ifalt()be asynchronous that will give other problems.– Sergio
@Sergio, all right I believe and I know you know what you are saying. But I could give an example of what your solution would be, as an answer. I accepted the one because it seems to me the most suitable so far. I edited the answer to which
alt()receive arguments– Hula Hula
I gave an answer with what I would do in the case that seems to be yours. If the question is more detailed it is easier to answer.
– Sergio