Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

javascript - Multiple of the same component spawning the same modal on the same page?

I'm using Vue, and I have a component that outputs a button. That button opens a modal, also part of that component. This works.

If I have multiple of those buttons on the page then the modal is spawned twice. I understand why, but that's not what I want to happen.

Below is the code:

<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>

Is there a way to make this modal totally unique, so it isn't duplicated? It will always have the same content no matter what button is pressed.

The other questions on StackOverflow around this problem are focussed on the pattern of tabled data with 'Edit' buttons next to a row that spawns a modal with a form in it to edit that data - that's not what I'm trying to achieve. The modal is always the same and will always have the same data in it. I want to achieve a single component that I can drop in anywhere to allow a user to open this modal, so the solution isn't to put the modal outside of this component.

Thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The modal must be in its own component, or it will inevitably be duplicated every time you write it in the template. Create a component for the modal which you can import just once into App.vue. You can toggle it with a Vuex state.

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;
  }
}

Now from any component you can use the mutation to show the modal:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...