在Vue上执行Ajax响应成功后,如何显示模式?

时间:2018-09-11 01:12:01

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

我的Vue组件是这样的:

<template>
    ...
    <b-modal id="modalInvoice" size="lg"  title="Invoice">
        <Invoice/>
        <div slot="modal-footer" class="w-100"> 
            <b-btn size="sm" class="float-right" variant="warning" @click="show=false">
                <i class="fa fa-print"></i> Print
            </b-btn>
        </div>
    </b-modal>

    ...
        <b-btn variant="warning" class="btn-square mt-2" v-b-modal.modalInvoice @click="checkout()"><i class="fa fa-credit-card-alt"></i>Checkout</b-btn>
    ...
</template>
<script>
    ...
    export default {
        ...
        methods: {
            checkout() {
                var request = new Request(ApiUrl.orders, {
                    method: 'post',
                    body: JSON.stringify(this.$session.get(SessionKey.Cart)),
                    headers: new Headers({
                        'Authorization': 'bearer ' + this.$session.get(SessionKeys.ApiToken),
                        'Content-Type': 'application/json'
                    })
                });
                fetch(request).then(r=> r.json())
                    .then(r=> {
                        this.items = r.data
                    })
                    .catch(e=>console.log(e));
            }
        }
    }
</script>

如果单击了按钮结帐,则模态显示而无需先等待响应ajax成功

我想在响应ajax成功之后进行模态显示

我该怎么办?

1 个答案:

答案 0 :(得分:1)

使用v-model来控制模式可见性:

<b-modal id="modalInvoice" size="lg"  title="Invoice" v-model="show">
    <Invoice/>
    <div slot="modal-footer" class="w-100"> 
        <b-btn size="sm" class="float-right" variant="warning" @click="show=false">
            <i class="fa fa-print"></i> Print
        </b-btn>
    </div>
</b-modal>

这样,您可以在获取返回时显式设置show属性:

<script>
    ...
    export default {
        ...
        // a data property for the v-model to bind
        data () {
            return {
                 show: false
            }
        }
        methods: {
            checkout() {
                var request = new Request(ApiUrl.orders, {
                    method: 'post',
                    body: JSON.stringify(this.$session.get(SessionKey.Cart)),
                    headers: new Headers({
                        'Authorization': 'bearer ' + this.$session.get(SessionKeys.ApiToken),
                        'Content-Type': 'application/json'
                    })
                });
                fetch(request).then(r=> r.json())
                    .then(r=> {
                        this.items = r.data
                        // toggle the value of show to display the modal
                        this.show = true
                    })
                    .catch(e=>console.log(e));
            }
        }
    }
</script>