How to redirect PC address to mobile address in Vue

How to redirect PC address to mobile address in Vue

Requirements: The PC side and the mobile side are two independent projects. The contents of the two projects are basically the same, and there are regularities in the way the links are combined. The requirement is to redirect to the corresponding page on the mobile side when accessing the URL link on the PC side on the mobile side.

The way to implement this requirement is relatively clear. My general idea is to monitor each incoming routing request at the routing guard and analyze whether the request is accessed by the mobile terminal. If not, the routing request is directly released; if so, the routing path to be entered is analyzed, the necessary fields in the path are extracted, and the combination is called a new mobile terminal link.

It involves three knowledge points: 1. Routing guard, 2. Client judgment, 3. Regular expression text extraction. Next, I will explain these points one by one, and attach the source code of the entire development process for your reference, learning or criticism.

1. Routing Guard

  • to: the route to enter
  • from: From which route to access
  • next: routing control parameters, commonly used next(true), and next(false)
//All routing requests will pass through the routing guard,
router.beforeEach((to, from, next) => {
	
    //Access link such as: http://localhost/page/detail/IUKGEQ/108/9933/32279/8
    //The access path is: /page/detail/IUKGEQ/108/9933/32279/8
  	let toUrl = to.path;
                                                                       
    //This route request is released next();

});

2. Determine the client

navigator.userAgent : Gets the value of the user agent header used by the browser for HTTP requests

 if (typeof window !== 'undefined' && typeof window.navigator !== 'undefined') {
            if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
            	//Processing business logic on mobile side}else{
				//Processing business logic on the computer side}
   }

3. Regular Expression (JS)

grammar

/regular expression body/modifiers (optional)

Modifiers

expression describe
i Performs a case-insensitive match.
g Perform a global match (find all matches instead of stopping after the first one).
m Performs a multi-line match.

search()

The search() method is used to search for a specified substring in a string, or to search for a substring that matches a regular expression, and return the starting position of the substring. If not, returns **-1**.

// Case insensitive var index = 'Hello World!'.search(/world/i);

replace()

The replace() method is used to replace some characters in a string with other characters, or to replace a substring that matches a regular expression.

var txt = 'Microsoft'.replace("Microsoft","World");

test()

The test() method is used to check whether a string matches a pattern. If the string contains matching text, it returns true, otherwise it returns false

var flag = /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent);

exec()

The exec() method is used to retrieve matches of a regular expression within a string.

This function returns an array containing the matching results. If no match is found, the return value is null.

var matchParams = /(\d{1,3})\/(\d{4,6})\/(\d{4,6})/.exec('/page/detail/IUKGEQ/108/9933/32279/8')

Regular syntax reference: https://www.runoob.com/regexp/regexp-syntax.html

4. Source code:

export default ({ app }) => {
    app.router.beforeEach((to, from, next) => {
        if (typeof window !== 'undefined' && typeof window.navigator !== 'undefined') {
            if(!/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
                //If accessed from a computer, next() will be released directly;
            }else{

                var sCode = '';
                let toUrl = to.path;
                //Identifier acquisition method 1: Get from the request link //For example: /page/detail/IUKGEQ/108/9933/32279/8
                //For example: /IUKGEQ
                //Regular expression to extract the six uppercase letters in the connection let matchArr = toUrl.match('\/([AZ]{6})');
                if((sCode=='' || sCode == null || sCode == undefined) && matchArr != null){
                    sCode = matchArr[1];
                }
    
                //Identification acquisition method 2: initiate a request to obtain the Code 
                //For example: /swpu
                let matchArr2 = toUrl.match('\/([az]{3,})');
                if((sCode=='' || sCode == null || sCode == undefined) && matchArr2 != null){
                    var param = matchArr2[1];
                    getSInfo2(param)
                    .then(res => {
                      if (res.data.code) {
                        sCode = res.data.code;
                        //Route jump mobileRouteCombine(toUrl,sCode);
                      } else {
                        // Can't find code
                        next();//release}
                    })
                    .catch(err => {
                        next(); //release });
                }
                //If the above two methods cannot retrieve the code, just release it if(sCode=='' || sCode == null || sCode == undefined){
                    next();
                    return;
                }else{
                    //Route jump mobileRouteCombine(toUrl,sCode);
                }
            }
        }
        next();
    })
}

/**
 * Mobile routing reorganization* @param {URL address to be visited} toUrl 
 * @param [code] sCode 
 */
function mobileRouteCombine(toUrl,sCode){
    var wxHomeUrl = conf.weixin + '/build/index.html?scode=' + sCode + '#/';
                
    // If toUrl is in the form of /IUKGEQ, it will directly jump to the WeChat homepage if(toUrl.length <= 7){
        location.href = wxHomeUrl;
    }

    //Article listif(toUrl.indexOf('/page/list/') != -1){
        let matchParams = toUrl.match('(\\d{1,3})\/(\\d{4,6})'); 
        let catId = matchParams[2];
        let versionId = matchParams[1]; //version id
        var url = wxHomeUrl + 'articleList?catId=' + catId;
        location.href = url;     
    }

    //Article detailsif(toUrl.indexOf('/page/detail/') != -1){
        let matchParams = toUrl.match('(\\d{1,3})\/(\\d{4,6})\/(\\d{4,6})'); 
        let infoId = matchParams[3];
        let catId = matchParams[2];
        let versionId = matchParams[1]; //version id
        var url = wxHomeUrl + 'articleDetail?infoId=' + infoId + '&catId=' + catId;
        location.href = url;     
    }
}

This is the end of this article about redirecting PC address to mobile terminal in vue. For more relevant vue address redirection content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue-Element-Admin integrates its own interface to realize login jump
  • Implementing parameter jump function in Vue project
  • Detailed explanation of Vue's hash jump principle
  • How to implement vue page jump
  • Vue implements login, registration, exit, jump and other functions
  • Routing in Vue is not counted in history operations

<<:  How to keep running after exiting Docker container

>>:  Analysis of the HTML writing style and reasons of experienced people

Recommend

VUE introduces the implementation of using G2 charts

Table of contents About G2 Chart use Complete cod...

How to deploy hbase using docker

Standalone hbase, let’s talk about it first. Inst...

This article will help you understand the life cycle in Vue

Table of contents 1. beforeCreate & created 2...

Use CSS's clip-path property to display irregular graphics

clip-path CSS properties use clipping to create t...

Detailed explanation of the use of React.cloneElement

Table of contents The role of cloneElement Usage ...

Pagination Examples and Good Practices

<br />Structure and hierarchy reduce complex...

Handwritten Vue2.0 data hijacking example

Table of contents 1: Build webpack 2. Data hijack...

JS 4 super practical tips to improve development efficiency

Table of contents 1. Short circuit judgment 2. Op...

Native JS encapsulation vue Tab switching effect

This article example shares the specific code of ...

JS implements a simple brick-breaking pinball game

This article shares the specific code of JS to im...