【问题标题】:Prop value isn't updating in child component Vue.js子组件 Vue.js 中的道具值未更新
【发布时间】:2019-06-13 13:21:25
【问题描述】:

我正在添加一种方法,让父 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 但它不起作用。我如何让这个每次运行?

【问题讨论】:

  • 你能创建sandbox吗?
  • 创建codesandbox.io 更好,但我可以说的一件事是,对于此类基本任务,您的方式不必要地复杂。
  • 谢谢@Lahori 你会怎么做呢?
  • 一种方法可能是让覆盖将模态包裹在模态组件中。使用位置:固定,z-index:最高,你应该很好。
  • 全局事件总线可能是另一种选择 alligator.io/vuejs/global-event-bus

标签: javascript vue.js frontend vue-component vue-router


【解决方案1】:

当组件必须跨不同的父/子级别相互通信时,全局事件总线可以提供帮助。下面是一篇很好的文章:

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

注意:但一定要在必要时才使用,并在组件的beforeDestroy生命周期中移除监听器

【讨论】:

    猜你喜欢
    • 2019-10-05
    • 1970-01-01
    • 2019-07-08
    • 2021-08-09
    • 2018-08-16
    • 2017-04-30
    • 1970-01-01
    • 2018-07-02
    • 2017-07-08
    相关资源
    最近更新 更多