Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue: Update Component data from Vue instance

Tags:

vue.js

vuejs2

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} } });
like image 678
Green_qaue Avatar asked Nov 14 '17 09:11

Green_qaue


1 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>
like image 65
Richard Matsen Avatar answered Oct 02 '22 08:10

Richard Matsen