I want to update data in a component from my Vue instance. Finding plenty of examples on how to do the opposite, but nothing on this.
Say I have:
Vue.component('component', {
props: {
prop: {
default: null
}
},
template: '#template',
data: function () {
return {
open: false
};
}
});
Now I would like to set open
to true
from my Vue instance:
var root = new Vue({
el: '#root',
data: {},
methods: { updateComponentData: function() {//set open to true} } });
You should be able to do it with a Child Component Ref.
<script type="text/x-template" id="template" ref="component">
<div>Hello, {{ name }}!</div>
</script>
var root = new Vue({
el: '#root',
data: {},
methods: {
updateComponentData: function() {
this.$refs.component.open = true
}
}
});
Working example
const Child = Vue.component('child', {
template: `
<div>
<h2>Component1</h2>
<div>Hello, {{ title }}! <strong>{{ open }}<strong></div>
</div>
`,
data() {
return {
title: 'component',
open: false
}
}
});
var root = new Vue({
el: '#app',
components: {
Child
},
methods: {
updateComponentData: function() {
//console.log('updateComponentData', this.$refs)
this.$refs.component1.open = true
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
<h2>Parent</h2>
<button v-on:click="updateComponentData">Click me true</button>
<child ref="component1"></child>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With