0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vue.js で 変更したページから遷移する際、編集破棄確認メッセージを出力したい

Last updated at Posted at 2020-01-20

色々とやっつけですが、書きました。

  • (アンチパターンかと思いますが、)下記コードを mixinとしてまとめて使ってます。
  • ページコンポーネントで、mixinをimportして使ってください。
  • 適したタイミングで addWatchEventsFor メソッドを呼びます。引数で渡した名前のプロパティの値が変更されたら、フラグが立ちます。
  • フラグが立った状態でページ遷移をしようとすると、「よろしいですか?」のメッセージが出ます。
confirmEditDiscard.js
export default {
  data() {
    return {
      //対象オブジェクトが変更されたか
      isWatchPropChanged: false
    };
  },
  /**
   * 対象オブジェクトの変更監視イベントを追加する。
   */
  methods: {
    addWatchEventsFor(watchPropName) {
      this.$watch(
        watchPropName,
        // 変更があったらフラグを立てる
        function() {
          this.isWatchPropChanged = true;
        },
        { deep: true }
      );
    }
  },
  beforeRouteLeave(to, from, next) {
    // 確認画面へは、チェックせずページ遷移
    const componentName = this.$options.name;
    if (componentName === to.name.replace("Confirm", "")) {
      next();
      return;
    }
    // 変更がない場合も、チェックせずページ遷移
    if (!this.isWatchPropChanged) {
      next();
      return;
    }

    window.confirm("編集データは破棄されます。よろしいですか?")
      ? next()
      : next(false);
  }
};

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?