Vue: Update Component data from Vue instance

Viewed 37784

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} } });
2 Answers

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>

I just played with your code and the following codes works perfect please do try that. I have used Vue 'ref'. Add ref attribute in your component and then you can access that specific components data from parent.

Vue.component('component', {
    props: {
        prop: {
            default: null
        }
    },
    template: '#template',
    data: () => ({
        open: false
    })
});
var root = new Vue({
    el: '#root',
    data: () => ({}),
    methods: {
        updateComponentData: function() {
         this.$refs.myComponent.open = true
        }
    },
});
<script src="https://unpkg.com/vue"></script>
<div id="root">
   <button @click="updateComponentData">Change</button>
    <hr>
    <component ref='myComponent'></component>
</div>
<script type="text/x-template" id="template" ref="component">
    <div>Open: {{ open }}!</div>
</script>

Related