【问题标题】:Multiple of the same component spawning the same modal on the same page?在同一页面上产生相同模式的多个相同组件?
【发布时间】:2021-01-08 17:38:18
【问题描述】:

我正在使用 Vue,并且我有一个输出按钮的组件。该按钮打开一个模式,也是该组件的一部分。这行得通。

如果我在页面上有多个这样的按钮,那么模态框会生成两次。我明白为什么,但这不是我想要发生的。

下面是代码:

<template>    
    <div>
        <button @click="$bvModal.show('edit-profile-modal')" class="btn btn-sm btn-secondary mt-3">Edit</button>

        <b-modal id="edit-profile-modal" ref="editProfileModal" :ok-only="true">
            <template #modal-title>
                Edit your profile
            </template>
            <div class="d-block text-center">
                
            </div>
        </b-modal>
    </div>
</template>

<script>
    export default {
        props: {
        },

        data() {
            return {};
        },

        mounted() {
        },

        computed: {
        },

        methods: {
        }
    }
</script>

有没有办法让这个模式完全独一无二,所以它不会重复?无论按下什么按钮,它都将始终具有相同的内容。

StackOverflow 上围绕此问题的其他问题集中在表格数据的模式上,该模式带有“编辑”按钮的行旁边会生成一个带有表单的模式来编辑该数据 - 这不是我想要的达到。模态总是相同的,并且总是有相同的数据。我想实现一个可以放在任何地方的单个组件以允许用户打开此模式,因此解决方案不是将模式放在此组件之外。

谢谢

【问题讨论】:

标签: javascript vue.js bootstrap-vue


【解决方案1】:

modal必须在自己的组件里,不然每次写在模板里都难免重复。为模态框创建一个组件,您只需将其导入 App.vue 一次。您可以使用 Vuex 状态切换它。

Modal.vue

<b-modal>
...
</b-modal>

App.vue

<template>
  <div>
    ...
    <Modal v-show="showModal" />
  </div>
</template>
computed: {
  showModal() {
    return this.$store.state.showModal;
  }
}

store.js

state: {
  showModal: false
},
mutations: {
  toggleModal(state, isShown) {
    state.showModal = isShown;
  }
}

现在,您可以从任何组件中使用突变来显示模态:

methods: {
  showModal() {
    this.$store.commit('toggleModal', true);
  }
}

【讨论】:

    【解决方案2】:

    我知道这有点老了,但我在摆弄 Bootstrap Vue 的 Modals 时偶然发现了这个问题,并认为我会添加一个替代解决方案。

    BvModal 通过 id 来识别模板,当调用 show 函数时,它会显示所有带有该 ID 标记的匹配模板。所以知道了这一点,我们所要做的就是使 ID 独一无二!

    一种偷偷摸摸的方法是利用 Vue 分配给它的组件的 uid:

    <template>    
    <div>
        <button @click="$bvModal.show(`edit-profile-modal-${_uid}`)" class="btn btn-sm btn-secondary mt-3">Edit</button>
    
        <b-modal :id="`edit-profile-modal-${_uid}`" ref="editProfileModal" :ok-only="true">
            <template #modal-title>
                Edit your profile
            </template>
            <div class="d-block text-center">
                
            </div>
        </b-modal>
    </div>
    

    请注意,我们对 $bvModal.show 函数和 b-modal 的 id 属性都使用了模板文字。如果您觉得"'edit-profile-modal-' + _uid" 看起来更好,您也可以轻松使用。

    这将使您在页面上拥有任意数量的相同组件,而 BvModal 不会混淆哪个模式属于哪个组件,也无需创建自定义组件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      相关资源
      最近更新 更多