【问题标题】:Close modal by using back button with hash route使用带有哈希路由的后退按钮关闭模式
【发布时间】:2021-04-21 13:20:49
【问题描述】:

我在 vuejs 中有一个模态,我通过传递 isActive 属性来打开/关闭,我想在用户单击后退按钮时关闭模态。

当模式打开时,我将哈希 #modal 添加到 url,当模式关闭时,我删除哈希。

我试图在用户单击后退按钮时关闭模式,但目前它没有,它只是删除了哈希。

如果我单击 close() 方法,模式将关闭,因此看起来 eventListener() 无法正常工作。

当用户点击后退按钮时如何关闭模态框?

modal.js

import { mapActions, mapGetters } from 'vuex';
    
export default {
  props: {
    isActive: {
      type: Boolean,
      default: false,
    },
  },
   computed: {
     hashChange() {
       console.log(this.isActive)
       if(this.isActive) {
         window.location.assign('#modal')
        } else {
          history.replaceState({}, document.title, window.location.href.split('#')[0]);
        }
      },
    },
    methods: {
      close() {
        this.$emit('close');
      },
    },
    mounted() {
      window.addEventListener('hashchange', this.close());
    },
    destroyed() {
      window.addEventListener('hashchange', this.close());
    },
  };

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    HashChange 是基于 isActive 值,而 isActive 值是基于 hashChange 的,所以它是循环的,当然这种方式行不通,你可以直接听如下的后退按钮并完全删除 hashChange,在这种情况下它是没用的:

     methods: {
        close() {
          this.$emit('close');
        },
      },
      mounted () {
        document.addEventListener("backbutton", this.close, false);
      },
      beforeDestroy () {
        document.removeEventListener("backbutton", this.close);
      }
    

    在路由器中添加:

    // This listener will execute before router.beforeEach only if registered
    // before vue-router is registered with Vue.use(VueRouter)
    
    window.popStateDetected = false
    window.addEventListener('popstate', () => {
      window.popStateDetected = true
    })
    
    
    router.beforeEach((to, from, next) => {
      const IsItABackButton = window.popStateDetected
      window.popStateDetected = false
      if (IsItABackButton && from.name === //The name of the route you are using) {
        next(false) 
      }
      next()
    })
    

    【讨论】:

    • 谢谢,但如果我点击后退按钮,它似乎仍然返回而不是关闭模式
    • 你可以用 vue 路由器处理这个问题,我编辑我的答案给你看一个例子
    • @tomharrison 或者你可以尝试 history.replaceState({} inside close
    猜你喜欢
    • 2018-01-24
    • 2017-03-04
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 2016-06-11
    相关资源
    最近更新 更多