Vuejs:在路线更改之前显示确认对话框

时间:2018-04-30 04:47:31

标签: javascript vue.js vuejs2 vue-component vue-router

在我的vueJS项目中,我想在当前路线发生变化之前显示确认对话框。 enter image description here

是的,它应该重定向到下一个所需的路线,否则保持在同一路线上。

知道如何实现它吗?

提前致谢。

4 个答案:

答案 0 :(得分:12)

您可以使用组件内保护 beforeRouteLeave。见https://router.vuejs.org/en/advanced/navigation-guards.html

演示:https://codesandbox.io/s/jzr5nojn39(尝试在家中导航,第1页,第2页)

示例代码(使用vuejs-dialog作为确认对话框):

    beforeRouteLeave (to, from, next) {
        this.$dialog.confirm('Do you want to proceed?')
        .then(function () {
            next();
        })
        .catch(function () {
            next(false);
        });
    }

如果要继续,请使用next()

如果要取消重定向,请使用next(false)

答案 1 :(得分:3)

  

已接受的答案显示了如何使用vuejs-dialog来完成。但是,如果您不想使用此库,请检查以下内容:

说您有一个包含3个选项的对话框:

关闭对话框 =>调用closeDialog()并停留在同一页面

保存更改 =>调用saveChanges()保存更改并导航

放弃更改 =>呼叫discardChanges()导航而不保存更改

  data: () => ({
    to: null,
    showDialog: false
  }),

  beforeRouteLeave(to, from, next) {
    if (this.to) {
      next();
    } else {
      this.to = to;
      this.showDialog = true;
    }
  },

  methods: {
    closeDialog() {
      this.showDialog = false;
      this.to = null;
    },

    saveChanges() {
      // add code to save changes here
      this.showDialog = false;
      this.$router.push(this.to);
    },

    discardChanges() {
      this.showDialog = false;
      this.$router.push(this.to);
    }
  }

See it in action in codesandbox

外带这里的主要外带是beforeRouteLeave导航卫士,如果数据中的to属性为空,我们不允许用户离开。唯一不能为null的情况是用户在对话框中单击“保存”或“放弃”按钮。

答案 2 :(得分:2)

VueJS拥有 In Component Navigation Guards ,例如beforeRouteUpdatebeforeRouteLeave

beforeRouteEnter (to, from, next) {
  // called before the route that renders this component is confirmed.
  // does NOT have access to `this` component instance,
  // because it has not been created yet when this guard is called!
},
...
beforeRouteLeave (to, from, next) {
  // called when the route that renders this component is about to
  // be navigated away from.
  // has access to `this` component instance.
}

答案 3 :(得分:0)

以下代码对我有用

 <v-btn @click="deleteDialog = true">Delete</v-btn>
      <v-dialog v-model="deleteDialog" max-width="500px">
       <v-card>
               <v-card-title style="font-size:20px" >Are you sure you want to archive?</v-card-title>
               <v-card-actions>
                   <v-spacer></v-spacer>
                   <v-btn color="red" style="font-size:15px" flat @click.native="deleteDialog = false">No</v-btn>
                   <v-btn color="green" style="font-size:15px" flat @click.native="deleteItem">Yes</v-btn>
               </v-card-actions>
           </v-card>
       </v-dialog>