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

Categories

0 votes
353 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...