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

TypeScript generic parameter default types and new strict compilation option

Table of contents Overview Create a type definiti...

Vue data two-way binding implementation method

Table of contents 1. Introduction 2. Code Impleme...

Detailed explanation of Vue development website SEO optimization method

Because the data binding mechanism of Vue and oth...

mysql create database, add users, user authorization practical method

1. Create a MySQL database 1. Create database syn...

Vue folding display multi-line text component implementation code

Folding display multi-line text component Fold an...

HTML basic syntax is convenient for those who are just starting to learn HTML

1.1 General marking A general tag consists of an ...

How to choose the format when using binlog in MySQL

Table of contents 1. Three modes of binlog 1.Stat...

Summary of MySQL password modification methods

Methods for changing passwords before MySQL 5.7: ...

Detailed instructions for installing mysql5.7 database under centos7.2

The mysql on the server is installed with version...

How to configure common software on Linux

When you get a new Linux server, you generally ha...

How to deal with too many Docker logs causing the disk to fill up

I have a server with multiple docker containers d...

A simple method to be compatible with IE6's min-width and min-height

If a website is widescreen, you drag the browser ...

Detailed explanation of Linux dynamic library generation and usage guide

The file name of the dynamic library file under L...