Vue-更改另一个组件的状态

问题描述 投票:0回答:3

我需要将isHidden值更新为true。我的代码分为以下几个部分:

// Profile.vue

<UserData
  v-bind:user_billing="user_billing"
  v-bind:user_profile="user_profile"
  ></UserData>
   <div class="col-12 px-0 my-3">
       <button @hide="hide"
               type="button"
               v-on:click="saveBillingData"
               class="btn btn-link color-link-ci btn-custom-hover border-0 rounded-pill pl-0">
                        Salva
       </button>

和/或UserData.vue

<template>
  <form v-on:change="enableSave()"
...
methods: {

 enableSave(){
// here i want change the isHidden status to false

}

如何更改状态?我已经尝试过this。$ parent / $ children,但是端点不正确。

vue.js vuejs2 vue-component
3个回答
0
投票

您可以在子组件中发出events并在父组件中对其作出反应。

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
投票

您可以使用ref attribute访问子组件。

您将必须在ref="Something"中添加<UserData>,然后使用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
 }
}

0
投票

您可以使用Custom Events将事件从子事件触发到父事件,如下所示:

  1. 在父母(个人资料):
<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. 在子项(UserData):
enableSave(){
     this.$emit("hide",false);
}
© www.soinside.com 2019 - 2024. All rights reserved.