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

The latest Linux installation process of tomcat8

Download https://tomcat.apache.org/download-80.cg...

MySQL database constraints and data table design principles

Table of contents 1. Database constraints 1.1 Int...

jQuery realizes the scrolling effect of table row data

This article example shares the specific code of ...

JS implements the rock-paper-scissors game

This article example shares the specific code of ...

How to build sonarqube using docker

Table of contents 1. Install Docker 2. Install so...

jQuery achieves full screen scrolling effect

This article example shares the specific code of ...

Use of nginx custom variables and built-in predefined variables

Overview Nginx can use variables to simplify conf...

win10 docker-toolsbox tutorial on building a php development environment

Download image docker pull mysql:5.7 docker pull ...

How to use CSS counters to beautify ordered lists of numbers

In web design, it is very important to use an org...

VMware Workstation download and installation detailed tutorial

Virtual machines are very convenient testing soft...

Linux uses if to determine whether a directory exists.

How to use if in Linux to determine whether a dir...

Linux sudo vulnerability could lead to unauthorized privileged access

Exploiting a newly discovered sudo vulnerability ...

Methods of adaptive web design (good access experience on mobile phones)

1. Add the viewport tag to the HTML header. At th...