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><divid="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 the first click gives error, saying:
Can not read property 'alt' of undefined / TypeError: this. $ refs.comp1 is undefined
When in the previous line this component ( this.item = true;
) should already exist defined
To get around this 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><divid="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 do not want or even seem at all to be the right one.
I'm looking for an alternative to this, have I implemented anything wrong, or should have done something I did not know / exist.