zoukankan      html  css  js  c++  java
  • 关于vue.js禁用浏览器返回问题以及路由的一些简单使用

    1、查了一下网上的资料,发现以下方法有效

    history.pushState(null, null, document.URL);
    window.addEventListener('popstate', function () {
        history.pushState(null, null, document.URL);
    });

    2、可是,有时候不能直接禁用,而是要返回指定的路由地址,于是:

    mounted() {
        if (window.history && window.history.pushState) {
            // 向历史记录中插入了当前页
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', this.goback, false);
        }
    },
    destroyed() {
        window.removeEventListener('popstate', this.goback, false);
    },

    其中this.goback()是mothods中的方法,可以自定义返回地址,例如:

    goback: function() {
        this.$router.push({
            path: '/orderdetails',
        });
        history.pushState(null, null, document.URL);
    },

    3、以上两个方法出现的情况都是因为浏览器有记录跳转路由,因为之前基本路由跳转都是用的router.push(),后来看了一下官网才知道,其实可以直接使用router.replace(),跟router.push很像,唯一的不同就是,他不会向history添加新记录,而是跟他的方法名一样,替换掉当前的history记录,他有两种方式:

      ①:声名式

    <router-link :to="..." replace>

      ②:编程式

    router.replace(...)

    需要注意的是,如果目的地和当前路由相同,只有参数发生了改变,则需要使用beforeRouteUpdate来响应这个变化

    由于使用路由参数时,原来的组件实例会被复用,组件的生命周期钩子也不会再被调用。

    所以,复用组件时,想对路由参数的变化做出响应的话,可以简单的watch(检测变化)$route对象:

    const User = {
      template: '...',
      watch: {
        '$route' (to, from) {
          // 对路由变化作出响应...
        }
      }
    }

    或者使用2.2中引入的beforeRouteUpdate导航守卫:

    const User = {
      template: '...',
      beforeRouteUpdate (to, from, next) {
        // react to route changes...
        // don't forget to call next()
      }
    }

    捕获所有路由或404 Not found路由

    {
      // 会匹配所有路径
      path: '*'
    }
    {
      // 会匹配以 `/user-` 开头的任意路径
      path: '/user-*'
    }

    当使用通配符路由时,请确保路由的顺序是正确的,也就是说含有通配符的路由应该放在最后。路由 { path: '*' } 通常用于客户端 404 错误。

    当使用一个通配符时,$route.params 内会自动添加一个名为 pathMatch 参数。它包含了 URL 通过通配符被匹配的部分:

    // 给出一个路由 { path: '/user-*' }
    this.$router.push('/user-admin')
    this.$route.params.pathMatch // 'admin'
    // 给出一个路由 { path: '*' }
    this.$router.push('/non-existing')
    this.$route.params.pathMatch // '/non-existing'
  • 相关阅读:
    爬虫-基于scrapy-redis两种形式的分布式爬虫
    爬虫-Scrapy框架(CrawlSpider)
    爬虫-User-Agent和代理池
    爬虫-scrapy框架之递归解析和post请求
    爬虫-scrapy数据的持久化存储
    爬虫-scrapy框架简介和基础应用
    爬虫-移动端数据爬取
    爬虫-图片懒加载技术、selenium和PhantomJS
    爬虫-验证码处理
    爬虫-requests模块
  • 原文地址:https://www.cnblogs.com/chao202426/p/11445093.html
Copyright © 2011-2022 走看看