Vue js-从对话框获取答案以确认带有Vue Router + Vuetify的导航

Mar*_*sky 2 vue.js vue-router vue-component vuejs2 vuetify.js

如果我有一个带有vuetify对话框的vue模板(但实际上是任何对话框),如何使用它来确认在vue-router的beforeRouteLeave方法中导航离开该页面?

dialogTest.vue:

<template>
    <v-container>
        <v-layout>
            <v-dialog v-model="dialog" max-width="290" ref="popup">
                <v-card>
                    <v-card-title class="headline">Are you sure you wish to leave this page?</v-card-title>
                    <v-card-text>Better think long and hard.</v-card-text>
                    <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn color="primary darken-1" flat="flat" @click.native="dialog = false">Nah</v-btn>
                        <v-btn color="primary darken-1" flat="flat" @click.native="dialog = false">Yah</v-btn>
                    </v-card-actions>
                </v-card>
            </v-dialog>
        </v-layout>
    </v-container>
</template>

<script src="./dialogTest.ts"></script>
Run Code Online (Sandbox Code Playgroud)

dialogTest.ts:

import Vue from 'vue';
import { Component } from 'vue-property-decorator';

Component.registerHooks([
    'beforeRouteLeave'
]);

@Component
export default class DialogTestComponent extends Vue {

    dialog: boolean = false;

    beforeRouteLeave(to: Object, from: Object, next: Function) {
        console.log('beforeRouteLeave');

        //this works, but obviously doesn't use our dialog -> how do we get yah or nah response from dialog instead?
        const answer =  window.confirm('Do you really want to leave? you have unsaved changes!')
        if (answer) {
            next()
        } else {
            next(false)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

bbs*_*nbb 5

我喜欢承诺。给您的对话框一个pop()方法,该方法返回一个诺言,然后在用户选择时使用true或false来解决诺言。或从单元测试中调用clickYah()。像这样

// in your dialog component....
data(){
    return {active : false, resolve: null};
}
methods : {
    pop(){
        this.active = true;
        return new Promise(function(resolve, reject){
            this.resolve = resolve;
        });
    },
    clickYah(){
        this.active = false;
        this.resolve(true);
    },
    clickNah(){
        this.active = false;
        this.resolve(false);
    }
}

// then to call it...
this.$refs.modalDialog.pop()
.then(confirmResult => next(confirmResult));
Run Code Online (Sandbox Code Playgroud)