簡體   English   中英

屬性值未在子組件Vue.js中更新

[英]Prop value isn't updating in child component Vue.js

我為父App.vue添加了一種方法, App.vue告訴所有子組件關閉您打開的每個模式,並讓任何給定的子組件告訴父如果某人單擊主應用div則可以隱藏覆蓋。 因此,例如,如果服務頁面打開了一個模態以查看一些詳細信息,則將在父App.vue組件中設置一個疊加層,如果我單擊模態之外的任何位置,則模態將關閉,子級將關閉告訴父母關閉覆蓋層。 我以這種方式設置它,以便它在全球范圍內可用,而不是孤立於單個組件。

<template>
  <div id="app" v-cloak :class="{'overlay-layer' : overlay.active}" v-on:click="close($event)">

    <Header/>

    <transition>
      <router-view v-on:overlay="overlay.active = $event" :closeAllModals="overlay.close"/>
    </transition>

    <Footer/>

  </div>
</template>

<script>
import Header from '@/components/header/Header.vue';
import Footer from '@/components/footer/Footer.vue';

export default {
  components: {
    Header,
    Footer
  },
  props: {
    closeAllModals: Boolean
  },
  data: function() {
    return {
      overlay: { active: false, close: false }
    };
  },
  methods: {
    close(e) {
      if (this.overlay.active && e.toElement.id === 'app') {
        this.overlay = {
          active: false,
          close: true
        }
      }
    }
  }
};
</script>

問題是,這僅執行一次,因此例如在服務頁面中,我有:

import Header from '@/components/header/Header.vue';
import Footer from '@/components/footer/Footer.vue';

export default {
  name: 'services',
  components: {
    Header,
    Footer
  },
  props: {
    closeAllModals: Boolean
  },
  data: function() {
    return {
      overlay: false,
      activeMember: Object,
    };
  },
  methods: {
    setActiveMember(member, open) {
      this.activeMember = member;
      if (open) {
        this.activeMember.active = true;
        this.overlay = true;
      } else {
        this.activeMember.active = false;
        this.overlay = false;
      }
      this.$emit('overlay', this.overlay);
      this.$forceUpdate();
    },
  watch: {
    closeAllModals: function() {
      this.activeMember.active = false;
      this.overlay = false;
      this.$forceUpdate();
      console.log('runs once');
    }
  }
};

因此這有效,但僅在第一次有效。 該道具僅將更新后的值發送給孩子一次。 我嘗試在孩子中觀看道具並使用forceUpdate,但它不起作用。 如何使每次運行?

當組件必須在不同的父/子級別之間相互通信時,全局事件總線可能會有所幫助。 以下是關於此的很好的寫法:

https://alligator.io/vuejs/global-event-bus

注:但可以肯定的只有在必要時才使用,並刪除在聽眾beforeDestroy組件的生命周期

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM