首页 文章

管理哪个bootstrap-vue模式通过vuex状态打开

提问于
浏览
2

我正在构建一个需要对多个bootstrap-vue模块进行排序的应用程序 . 具体来说,嵌套组件中的按钮应该打开“manage”模式 . 'manage'模式包含的按钮在点击时应该关闭'manage'模式并打开另一个模态(例如'edit','add','complete'等) .

而不是上下传递道具/发射事件以便可以从不同的嵌套组件触发这些事件,我希望在我的商店中有一个值 this.$store.state.general.activeModal ,它确定显示哪个模态(如果有的话)

Question: How can I create a set of modals in my main app page that render if a value in the state is changed?

我的主应用程序将如下所示:

<template>
   <app-stuff />
   <b-modal id="modal1" />
   <b-modal id="modal2" />
   <b-modal id="modal3" />
</template>

例如modal1应该在 this.$store.state.general.activeModal 设置为'modal1'时显示,并在值更改为其他值时关闭 .

我尝试创建一个计算变量"showModal1",当 store.etc.activeModal=='modal1' 时为true,否则为false,然后使用 v-modal="showModal1" 来显示/隐藏模态,但它只是在每次商店中的值匹配时创建两个模态副本(显然计算值触发)存储中的值更改后两次?)

任何帮助都会很棒!

3 回答

  • 0

    虽然不是bootstrap-vue,但我们已经使用简单的 v-if 指令成功使用了Bootstrap Modals . 如果条件为真,则模态仅显示/呈现 .

    使用Vuex,您可以为activeModal提供计算属性,并为 v-if="activeModal == 'modalName'" 提供每个模态的v-if . 在我们的模态中,我们使用Vue生命周期 mounted 来显示我们的模态,并注册一个emit(bootstrap-vue可能会以不同的方式处理...)

    $('#' + this.modalId).on('hide.bs.modal', () => { this.$emit('closeModal') //this would set the v-if in parent Component to false, un-rendering the modal component })

  • 0

    我建议你在观察者中使用 b-modal 组件的方法:.show()和.hide()来捕获你的状态突变:

    <template>
        <div>
            <b-modal ref="modal1" id="modal1"></b-modal>
            <b-modal ref="modal2" id="modal2"></b-modal>
            <b-modal ref="modal3" id="modal3"></b-modal>
        </div>
    </template>
    

    不要注意mapGetters,你必须看你的商店getter / state . 这里假设activeModal是你的状态值 .

    computed : {
        ...mapGetters([
            'activeModal'
        ])
    },
    watch : {
        activeModal(newActiveModal, oldActiveModal) {
            // If an old value was setted, we want to hide it in anyway.
            if (oldActiveModal) this.$refs[oldActiveModal].hide()
            // If the new value is falsy, do nothing
            if (!newActiveModal) return
    
            this.$refs[newActiveModal].show()
        }
    
    }
    
  • 0

    您可以为每个模态的可见性创建计算属性,例如:

    computed: {
      modal1Visible() {
        return this.$store.state.activeModal === 'modal1';
      }
    }
    

    然后设置b模态的 visible 属性:

    <b-modal :visible="modal1Visible" id="modal1">
    

    要处理结束模态,您可以将 hide 事件与设置 this.$store.state.activeModal 值的商店操作或变异结合使用,例如:

    <b-modal :visible="modal1Visible"
             @hide="$store.commit('activeModalSet', null)"
             id="modal1"
    </b-modal>
    

    这意味着如果您通过 v-b-modal 指令,关闭按钮或其他方法关闭模态:

    • 模态将发出 hide 事件

    • 将触发 activeModalSet 突变,将 this.$store.activeModal 设置为 null

    • modal1Visible 计算属性现在将评估为 false

    • 模态的 visible 属性将为false,因此将隐藏模态 .

相关问题