Vue2.0 implements adaptive resolution

Vue2.0 implements adaptive resolution

This article shares the specific code of Vue2.0 to achieve adaptive resolution for your reference. The specific content is as follows

1. Front-end framework: Vue2.0+elementUI 2.15.7

2. Development tools: VS Code

3. Install the required rack package:

"postcss-import": "12.0.1",
"postcss-loader": "4.0.1",
"postcss-pxtorem": "^5.1.1",

Check whether the "flexible" package is installed. If installed, uninstall or cancel the reference. The package file will conflict with the modified "flexible" file.

4. Create the flexibleEx.js file (this file is the flexible.js file that modifies the flexible package, which can be modified as needed) and place it in any desired location, such as under the "/src/utils" directory.

Then introduce "flexibleEx.js" into "main.js", such as:

import '@/utils/flexibleEx.js'

File code:

(function(win, lib) {
  var doc = win.document
  var docEl = doc.documentElement
  var metaEl = doc.querySelector('meta[name="viewport"]')
  var flexibleEl = doc.querySelector('meta[name="flexible"]')
  var dpr = 0
  var scale = 0
  var tid
  var flexible = lib.flexible || (lib.flexible = {})
 
  if (metaEl) {
    console.warn('The zoom ratio will be set according to the existing meta tags')
    var match = metaEl
      .getAttribute('content')
      .match(/initial\-scale=([\d\.]+)/)
    if (match) {
      scale = parseFloat(match[1])
      dpr = parseInt(1 / scale)
    }
  } else if (flexibleEl) {
    var content = flexibleEl.getAttribute('content')
    if (content) {
      var initialDpr = content.match(/initial\-dpr=([\d\.]+)/)
      var maximumDpr = content.match(/maximum\-dpr=([\d\.]+)/)
      if (initialDpr) {
        dpr = parseFloat(initialDpr[1])
        scale = parseFloat((1 / dpr).toFixed(2))
      }
      if (maximumDpr) {
        dpr = parseFloat(maximumDpr[1])
        scale = parseFloat((1 / dpr).toFixed(2))
      }
    }
  }
 
  if (!dpr && !scale) {
    var isAndroid = win.navigator.appVersion.match(/android/gi)
    var isIPhone = win.navigator.appVersion.match(/iphone/gi)
    var devicePixelRatio = win.devicePixelRatio
    if (isIPhone) {
      // Under iOS, for 2 and 3 screens, use the 2x solution, and for the rest, use the 1x solution if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {
        dpr = 3
      } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)) {
        dpr = 2
      } else {
        dpr = 1
      }
    } else {
      // For other devices, the 1x solution is still used dpr = 1
    }
    scale = 1 / dpr
  }
 
  docEl.setAttribute('data-dpr', dpr)
  if (!metaEl) {
    metaEl = doc.createElement('meta')
    metaEl.setAttribute('name', 'viewport')
    metaEl.setAttribute(
      'content',
      'initial-scale=' +
            scale +
            ', maximum-scale=' +
            scale +
            ', minimum-scale=' +
            scale +
            ', user-scalable=no'
    )
    if (docEl.firstElementChild) {
      docEl.firstElementChild.appendChild(metaEl)
    } else {
      var wrap = doc.createElement('div')
      wrap.appendChild(metaEl)
      doc.write(wrap.innerHTML)
    }
  }
 
  function refreshRem() {
    const whiteList = [
      '/managementKanban',
      '/productionKanban',
      '/controlBoard',
      '/main'
    ] // Do not redirect whitelist routes var width = docEl.getBoundingClientRect().width
    var rem = 0
 
    var hrefList = window.location.href.split('/')
    var url = hrefList[hrefList.length - 1]
    var url0 = url.split('?')
    var urlEnd
    if (url0.length > 0) {
      urlEnd = url0[0]
    }
    if (!whiteList.includes('/' + urlEnd)) {
      if (width / dpr <= 1980 && width / dpr > 768) {
        width = 1980 * dpr
        rem = width / 48
      } else if (width / dpr >= 5760) {
        width = 5760 * dpr
        rem = width / 48
      } else {
        width = 540 * dpr
        rem = width / 20
      }
      docEl.style.fontSize = rem + 'px'
      flexible.rem = win.rem = rem
    }
  }
 
  win.addEventListener(
    'resize',
    function() {
      clearTimeout(tid)
      tid = setTimeout(refreshRem, 300)
    },
    false
  )
  win.addEventListener(
    'DOMNodeInserted',
    function() {
      clearTimeout(tid)
      tid = setTimeout(refreshRem, 50)
    },
    false
  )
  win.addEventListener(
    'pageshow',
    function(e) {
      if (e.persisted) {
        clearTimeout(tid)
        tid = setTimeout(refreshRem, 300)
      }
    },
    false
  )
 
  if (doc.readyState === 'complete') {
    doc.body.style.fontSize = 12 * dpr + 'px'
  } else {
    doc.addEventListener(
      'DOMContentLoaded',
      function(e) {
        doc.body.style.fontSize = 12 * dpr + 'px'
      },
      false
    )
  }
 
  refreshRem()
 
  flexible.dpr = win.dpr = dpr
  flexible.refreshRem = refreshRem
  flexible.rem2px = function(d) {
    var val = parseFloat(d) * this.rem
    if (typeof d === 'string' && d.match(/rem$/)) {
      val += 'px'
    }
    return val
  }
  flexible.px2rem = function(d) {
    var val = parseFloat(d) / this.rem
    if (typeof d === 'string' && d.match(/px$/)) {
      val += 'rem'
    }
    return val
  }
})(window, window['lib'] || (window['lib'] = {}))

5. Modify the "build/utitls.js" file and add the following code:

function generateLoaders(loader, loaderOptions) {
    const loaders = options.usePostCSS ? [cssLoader] : [cssLoader];
 
    if (loader) {
      loaders.push({
        loader: loader + "-loader",
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      });
    }
 
    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: "vue-style-loader",
        publicPath: "../../"
      });
    } else {
      return ["vue-style-loader"].concat(loaders);
    }
  }

6. Modify the "postcssrc.js" in the directory

module.exports = {
    plugins: {
        'autoprefixer': {
            overrideBrowserslist: [
                'Android 4.1',
                'iOS 7.1',
                'Chrome > 31',
                'ff > 31',
                'ie >= 8'
            ]
        },
        'postcss-pxtorem': {
            rootValue: 37.5,
            propList: ['*']
        }
    }
}

7. Note: The interface adaptation problem has been solved, but there are still some problems with the interface presentation. Now you need to modify the abnormal interface yourself. Try to use rem for interface development and try not to use inline styles. These all need to be modified manually.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Sample code for implementing PC resolution adaptation in Vue
  • Vue3.0 adaptive operation of computers with different resolutions
  • Vue implements PC resolution adaptation operation

<<:  Introducing multiple custom fonts in CSS3

>>:  How to insert pictures into HTML pages and add map index examples

Recommend

8 examples of using killall command to terminate processes in Linux

The Linux command line provides many commands to ...

Solution to Chinese garbled characters when operating MySQL database in CMD

I searched on Baidu. . Some people say to use the...

SVN installation and basic operation (graphic tutorial)

Table of contents 1. What is SVN 2. Svn server an...

Automatically build and deploy using Docker+Jenkins

This article introduces Docker+Jenkins automatic ...

Web front-end performance optimization

Web front-end optimization best practices: conten...

W3C Tutorial (2): W3C Programs

The W3C standardization process is divided into 7...

Should I use Bootstrap or jQuery Mobile for mobile web wap

Solving the problem Bootstrap is a CSS framework ...

Solution to transparent font problem after turning on ClearType in IE

The solution to the transparent font problem after...

In-depth analysis of HTML semantics and its related front-end frameworks

About semantics Semantics is the study of the rel...

How to view nginx configuration file path and resource file path

View the nginx configuration file path Through ng...

Four methods of using JS to determine data types

Table of contents Preface 1. typeof 2. instanceof...

Web design skills: iframe adaptive height problem

Maybe some people have not come across this issue ...

Use of MySQL truncate table statement

The Truncate table statement is used to delete/tr...