【问题标题】:Vue: Detect when new component is mountedVue:检测何时安装新组件
【发布时间】:2020-04-10 16:33:21
【问题描述】:

我正在开发一种撤消功能,在用户单击“删除”按钮后,屏幕底部会弹出一个模式(类似于 gmail)。现在,我想在安装撤消组件时禁用“删除按钮”。撤消组件和显示它的组件无关,因此我无法$emit 事件并希望避免使用事件总线。我知道this.$options.components 保存有关已安装组件的信息-所以我基本上是在寻找watch 更改$options.components 的方法 非常感谢任何帮助!

【问题讨论】:

    标签: vue.js watch


    【解决方案1】:

    查看子组件内部属性并不是真正的 Vue 方式,像 $options 这样的属性被插件等使用,但你不应该在日常代码中真正使用它。

    理想情况下,您应该有一个 v-if 或一个将两者联系起来的事件,但似乎这是不可能的。

    因此,您应该与Vuex 共享状态,并基于此共享状态具有条件行为。比如:

    // store.js
    export default new Vuex.Store({
      state: {
        userCanUndo: false,
      },
      mutations: {
        setUserCanUndo(state, value) {
          state.userCanUndo = value;
        }
      },
    }
    
    // Undo.vue
    <template>
      <div v-if="userCanUndo">
        <!-- ... -->
      </div>
    </template>
    <script>
    import { mapState } from 'vuex';
    export default {
      computed: {
        ...mapState(['userCanUndo']),
      },
    }
    </script>
    
    // DeleteButton.vue
    <template>
      <button :disabled="userCanUndo" @click="delete">
        Delete
      </button>
    </template>
    <script>
    import { mapMutations, mapState } from 'vuex';
    export default {
      computed: {
        ...mapState(['userCanUndo']),
      },
      methods: {
        ...mapMutations(['setUserCanUndo']),
        delete() {
          // your delete code here
          this.setUserCanUndo(true);
          setTimeout(() => { this.setUserCanUndo(false); }, 2000);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 2020-01-20
      • 2021-07-25
      • 2019-11-28
      • 2021-10-30
      • 2020-11-14
      • 1970-01-01
      • 2023-03-14
      • 2019-11-12
      相关资源
      最近更新 更多