Operation method of PC terminal address jump mobile terminal in vue

  • 2021-12-04 09:28:28
  • OfStack

Requirements: The pc terminal and the mobile terminal are two independent projects, the contents of the two projects are basically the same, and the way of link combination can be followed regularly. The received requirement is to redirect to the corresponding page of the mobile terminal when the mobile terminal accesses the URL connection of the pc terminal.

The way to realize this requirement is relatively clear. My general idea is to listen to 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 released directly; If so, analyze the route path to be entered, extract the necessary fields in the path, and combine and call the new mobile link.

There are three knowledge points involved: 1. Routing guard, 2. Client judgment, 3. Regular text extraction. Next, explain 1 according to these points respectively, and attach the source code of the whole development process for reference or criticism and correction.

1. Routing Guard

to: Route to enter from: From which route next: Routing control parameters, commonly used next (true), and next (false)

// All routing requests pass through the routing guard, 
router.beforeEach((to, from, next) => {
	
    // Access links 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;
                                                                       
    // The route requests clearance 
    next();

});

2. Judge 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)) {
            	// Handle the business logic of the mobile terminal 
            }else{
				// Handle the business logic on the computer side 
            }
   }

3. Regular Expression (JS)

Grammar

/Regular expression body/modifier (optional)

Modifier

表达式 描述
i 执行对大小写不敏感的匹配。
g 执行全局匹配(查找所有匹配而非在找到第1个匹配后停止)。
m 执行多行匹配。

search()

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


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

replace()

The replace () method is used to replace 1 character with another 1 character in a string, or to replace a substring that matches a regular expression.


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

test()

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


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

exec()

The exec () method is used to retrieve a match of a regular expression in 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 the computer accesses, it will be released directly 
                next();
            }else{

                var sCode = '';
                let toUrl = to.path;
                // Identity acquisition method 1 Obtain from the request link 
                // Such as: /page/detail/IUKGEQ/108/9933/32279/8
                // Such as: /IUKGEQ
                // Regular expression extracts the  6 Identification of uppercase letters 
                let matchArr = toUrl.match('\/([A-Z]{6})');
                if((sCode=='' || sCode == null || sCode == undefined) && matchArr != null){
                    sCode = matchArr[1];
                }
    
                // Identity acquisition method 2 : Initiate a request to get Code 
                // Such as: /swpu
                let matchArr2 = toUrl.match('\/([a-z]{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;
                        // Routing jump 
                        mobileRouteCombine(toUrl,sCode);
                      } else {
                        //  Can't find out code
                        next();// Release 
                      }
                    })
                    .catch(err => {
                        next();// Release 
                    });
                }
                // If neither of the above two ways can be taken out, code , then release directly 
                if(sCode=='' || sCode == null || sCode == undefined){
                    next();
                    return;
                }else{
                    // Routing jump 
                    mobileRouteCombine(toUrl,sCode);
                }
            }
        }
        next();
    })
}

/**
 *  Mobile routing recombination 
 * @param { Visited url Address } toUrl 
 * @param [code] sCode 
 */
function mobileRouteCombine(toUrl,sCode){
    var wxHomeUrl = conf.weixin + '/build/index.html?scode=' + sCode + '#/';
                
    // toUrl For   Such as  /IUKGEQ  Form, jump directly to WeChat homepage 
    if(toUrl.length <= 7){
        location.href = wxHomeUrl;
    }

    // List of articles 
    if(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;     
    }

    // Details of the article 
    if(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;     
    }
}

Related articles: