使用其他组件中的按钮显示对话框

时间:2018-05-18 17:48:39

标签: javascript vue.js vuejs2

在我的vue2应用程序中,我有一个包含多个子组件的父组件。一个这样的子组件(我将其称为PaymentComponent)是一个用于捕获支付信息的简单对话框。

目前,应用程序中有几个地方显示付款对话框是有意义的。但是,我无法理解如何使用其他子组件中的按钮在PaymentComponent中显示对话框。

以下是PaymentComponent。关于如何使用共享相同父组件的另一个组件的按钮显示对话框的任何提示?

<template>
    <v-dialog v-model="paymentDialog" max-width="500">
        <card
            class='stripe-card'
            :class='{ complete }'
            stripe='pk_test_xxxxxxxxxxxxxxxxxxxx'
            :options='stripeOptions'
            @change='complete = $event.complete'>
        </card>

        <v-spacer></v-spacer>
        <v-btn color="green darken-1" flat="flat" @click.native="paymentDialog = false">Disagree</v-btn>
        <v-btn color="green darken-1" flat="flat" class="pay-with-stripe"  @click='pay' :disabled='!complete'>Agree</v-btn>
    </v-dialog>
</template>

<script>
    // import { stripeKey, stripeOptions } from './stripeConfig.json'
    import { Card, createToken } from 'vue-stripe-elements-plus'

    export default {
        name: 'stripe-payment',

        data () {
            return {
                complete: false,
                stripeOptions: {
                    // see https://stripe.com/docs/stripe.js#element-options for details
                },
                stripeKey: '',
                paymentDialog: false
            }
        },

        components: { Card },

        methods: {
            pay () {
                // createToken returns a Promise which resolves in a result object with
                // either a token or an error key.
                // See https://stripe.com/docs/api#tokens for the token object.
                // See https://stripe.com/docs/api#errors for the error object.
                // More general https://stripe.com/docs/stripe.js#stripe-create-token.
                createToken().then(data => console.log(data.token))
            }
        }
    }
</script>

2 个答案:

答案 0 :(得分:1)

  

所以你想从应用程序的任何地方打开模态。

一个解决方案将使用event bussee more here),您可以在其中从每个组件发出事件并在模态组件中侦听该事件。

另一种解决方案是使用vuexsee more here),您可以在其中切换(true,false)商店中的属性并侦听模态组件(必须是全局组件)以打开或关闭模态。

无论如何,我有类似于你的情况,并使用了一个很棒的图书馆,对我来说很完美,你可以用它:

1-使用this.$modal.show('name-of-modal')

打开模态

2-使用this.$modal.hide('name-of-modal')

隐藏模态

3-而不是模态,你也可以使用对话框和动态组件

了解更多read the docs

答案 1 :(得分:0)

您可以在PaymentComponent上使用ref,例如:

<stripe-payment ref="dialog"></stripe-payment>

在PaymentComponent中,定义open方法:

methods: {
  open() {
    this.paymentDialog = true
  }
}

然后在其他组件上,从open

调用此$root.$refs方法
methods: {
  openPayment() {
    this.$root.$refs['dialog'].open()
  }
}

Vuetify fiddle here