[Vuejs]-Vue โ€“ change state of another component

0๐Ÿ‘

You can use Custom Events to fire an event from the child to the parent as follows:

  1. In the parent (Profile):
<UserData
v-bind:user_billing="user_billing"
v-bind:user_profile="user_profile"
@hide="hide"
>
</UserData>
<button v-if="!isHidden"
        type="button" 
        v-on:click="saveBillingData"
        class="btn btn-link color-link-ci btn-custom-hover border-0 rounded-pill pl-0"
>
     Salva
</button>
methods:{
     hide(val){
          this.isHidden = val;
     }
}
  1. In the child (UserData):
enableSave(){
     this.$emit("hide",false);
}

0๐Ÿ‘

You can emit events in the child component and react to it in the parent component.

this.$emit('change-hidden', !this.isHidden);

Vue.config.devtools = false;
Vue.config.productionTip = false;

const UserData = Vue.component('user-data', {
  template: '<button @click="enableSave">Change</button>',
  props: ['isHidden'],
  methods: {
    enableSave() {
      this.$emit('change-hidden', !this.isHidden);
    }
  }
})

var app = new Vue({
  el: '#app',
  components: {
    UserData
  },
  data: {
    isHidden: true
  },
  methods: {
    onChangeHidden(e) {
      this.isHidden = e;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  isHidden : {{ isHidden }}
  <user-data :is-hidden="isHidden" v-on:change-hidden="onChangeHidden" />
</div>

0๐Ÿ‘

You could use the ref attribute to access a child component.

You would have to add ref="Something" in <UserData>, and access the component using this.$refs.Something

// Profile.vue

<UserData
v-bind:user_billing="user_billing"
v-bind:user_profile="user_profile"
ref="UserData"
>
</UserData>
...
 data: function () {
      return {
        isHidden: true,
    }
}

// UserData.vue

<template>
  <form v-on:change="enableSave()"
...
methods: {
 enableSave(){
    this.$refs.UserData.isHidden = false
 }
}

Leave a comment