【问题标题】:Display dialog using buttons in other components使用其他组件中的按钮显示对话框
【发布时间】:2018-05-18 17:48:38
【问题描述】:

在我的 vue2 应用程序中,我有一个包含多个子组件的父组件。一个这样的子组件(我将其称为 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>

【问题讨论】:

  • 请显示v-dialog组件

标签: javascript vue.js vuejs2


【解决方案1】:

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

一种解决方案是使用event bus (see more here),您可以在其中从每个组件发出一个事件并在模态组件中监听该事件。

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

无论如何,我的情况与您的情况相似,并且使用了一个非常适合我的出色库,并且您可以:

1- 使用this.$modal.show('name-of-modal')打开模态

2- 使用this.$modal.hide('name-of-modal')隐藏模式

3- 你也可以使用对话框和动态组件来代替模态组件

了解更多read the docs

【讨论】:

  • 事件总线运行良好!感谢您的建议!
  • 很高兴为您提供帮助。但我仍然建议使用该库!它非常有用
【解决方案2】:

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

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

在 PaymentComponent 中,定义一个open 方法:

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

然后在其他组件上,从$root.$refs 调用这个open 方法:

methods: {
  openPayment() {
    this.$root.$refs['dialog'].open()
  }
}

Vuetify fiddle here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    相关资源
    最近更新 更多