Here is a codepen I created: codepen
const sidebar = {
name: "sidebar",
template: "<p>SIDEBAR</p>",
data() {
return {
active: true
};
},
methods: {
test() {
alert("test: " + this.active)
}
}
};
new Vue({
el: '#app',
name: 'vue-instance',
data() {
return {
title: "Title of the page"
};
},
components: {
sidebar: sidebar,
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
{{ title }}
<sidebar ref="sidebar1">
</sidebar>
<button type="button" v-on:click="$refs.sidebar1.test()">Test sidebar</button>
<!-- {{ $refs.sidebar1.active }} this causes error! -->
{{ $refs }}
</div>
The issue arises from the commented line:
"message": "$refs.sidebar1 is undefined",
This means that during rendering, the parent component's $refs
collection is empty. However, upon clicking the button, $refs
can access sidebar1
correctly.
Why does this occur?
Is there a way to make {{ $refs.sidebar1.active }}
work in the parent component template?
Thank you for your help!