如何在vue组件中单击保存按钮后关闭模式?

时间:2017-07-14 14:31:41

标签: vue.js bootstrap-modal vuejs2 vue-component vuex

我的vue组件是这样的:

<template>
    <div ref="modal" class="modal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form>
                    ...
                    <div class="modal-footer">
                        ...
                        <button type="button" class="btn btn-success" @click="addPhoto">
                            Save
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        ...
        methods: {
            addPhoto() {
                const data = { id_product: this.idProduct };
                this.$store.dispatch('addImageProduct', data)
                    .then((response) => {
                        this.$parent.$options.methods.createImage(response)
                    });
            },
        } 
    }
</script>

如果我点击按钮addPhoto,它将调用addPhoto方法。

用于调用ajax的addPhoto方法。在响应ajax之后,它会将响应传递给父组件

中的createImage方法

运行后,模态不关闭。单击保存按钮后,模式是否应关闭

如何在调用createImage方法后关闭模态?

2 个答案:

答案 0 :(得分:2)

您不能以这种方式一起使用Bootstrap和Vue。每个人都希望控制DOM,他们会踩到彼此的脚趾。要一起使用它们,您需要wrapper components,以便Bootstrap可以控制组件内的DOM,Vue可以与包装器通信。

幸运的是,有一个项目为Bootstrap小部件创建了包装器组件。它是Bootstrap-Vue。当您按下确定按钮时,其模态将自动关闭。我把他们的模态示例变成了一种模糊的东西,就像你想要做的那样。

new Vue({
  el: '#app',
  methods: {
    clearName() {
      this.name = '';
    },
    addPhoto(e) {
      console.log("dispatch the request");
    }
  }
});
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap@next/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css" />

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<script src="//unpkg.com/babel-polyfill@latest/dist/polyfill.min.js"></script>
<script src="//unpkg.com/tether@latest/dist/js/tether.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>

<div id="app">
  <div>
    <b-btn v-b-modal.modal1>Launch demo modal</b-btn>

    <!-- Modal Component -->
    <b-modal id="modal1" title="Whatever" ok-title="Save" @ok="addPhoto" @shown="clearName">

      <form @submit.stop.prevent="submit">
        Form stuff...
      </form>

    </b-modal>
  </div>
</div>

答案 1 :(得分:-1)

<button type="button" class="btn btn-white" data-dismiss="modal">Close</button>

如果我理解了你想要的东西,那么将这个data-dismiss =“modal”添加到你想要用来关闭模态的任何按钮上。假设你有一个按钮上传图像点击你想要上传图像以及关闭模态然后将data-dismiss =“modal”添加到按钮属性,如上所示...