vue 获取 referer

有人封装了一个npm包,参考地址:https://www.npmjs.com/package/@tozd/vue-router-referer

@tozd/vue-router-referer

This NPM package provides a Vue plugin which exposes the route object of the previous route for Vue Router, under this.$router.referer.

Installation

This is a NPM package. You can install it using NPM:

$ npm install @tozd/vue-router-referer

It requires vue and vue-router peer dependencies:

$ npm install vue vue-router

Usage

First, you have to register the package as a Vue plugin:

import Vue from 'vue';
import VueRouterReferer from '@tozd/vue-router-referer';

Vue.use(VueRouterReferer);

源码很简单,如下:
export default function install(Vue, options) {
  Vue.mixin({
    beforeRouteEnter(to, from, next) {
      next((vm) => {
        if (vm.$router) {
          vm.$router.referer = from;
        }
      });
    },

    beforeRouteUpdate(to, from, next) {
      if (this.$router) {
        this.$router.referer = from;
      }
      next();
    },
  });
}

主要是利用了导航守卫做的。

posted @ 2021-10-27 10:38  屌丝大叔的笔记  阅读(1311)  评论(0编辑  收藏  举报