【问题标题】:Vue lifecycle hook - conditionally prevent creationVue 生命周期钩子 - 有条件地阻止创建
【发布时间】:2020-02-17 16:03:41
【问题描述】:

有没有办法防止在生命周期挂钩期间创建组件?例如:

beforeCreated() {
    //checking value from vuex store
    if (this.$store.state.attendeesCount >= this.$store.state.maxAttendees) {
        //prevent further propagation, don't create an instance of component
    }
}

情况是,我有一个包含多个子组件的父组件,其中包含用于创建与会者的表单(1 个组件 = 1 个与会者)。如果研讨会已经订满,我想阻止创建子组件。

更新: 父组件是十几个多行表单组件的基础组件,我不想在那里进行检查以使其尽可能抽象。

【问题讨论】:

  • 你为什么不在父组件的子组件标签上使用v-if呢?
  • 我认为您可以致电 this.$destroy() 但这可能不是一个干净/惯用的解决方案。可能更好的方法是在子组件上使用v-if
  • @Constantin Groß 是的,这将是最简单的方法,但我想避免修改父组件。它就像应用程序其余部分中许多其他多行表单的占位符。

标签: vue.js vue-component


【解决方案1】:

我并没有在生命周期挂钩期间实际阻止创建子组件,而是在满足条件后发出自定义事件。父组件监听这个自定义事件,并删除子组件实例。

孩子:

beforeCreate() {
    if (this.$store.state.attendeesCount >= 
    this.$store.state.maxAttendees) {
        this.$emit('preventCreation', {message: 'No more places'})
    }
}

家长:

<template>
    <component v-for="(item, index) in components"
         @preventCreation="preventCreation(index, $event)"
    ...
    >
    </component>
...
</template>
...
methods(){
    preventCreation(index, payload){
        this.components.splice(index, 1)
        alert(payload.msg)
    }
}

【讨论】:

    猜你喜欢
    • 2021-03-26
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 2020-01-15
    • 2017-11-22
    • 1970-01-01
    相关资源
    最近更新 更多