Table of Contents
Using the scale-box component
Set the device pixel ratio (device pixel ratio)
Set zoom attribute adjustment through JS Scaling ratio
Home Web Front-end Front-end Q&A Can vue be adaptive?

Can vue be adaptive?

Dec 30, 2022 pm 03:25 PM
vue Adaptive

vue can achieve self-adaptation. The methods to achieve self-adaptation are: 1. Install the "scale-box" component through the "npm install" or "yarn add" command, and use "scale-box" to implement self-adaptation. Equipped with zoom; 2. Adapt by setting the device pixel ratio; 3. Set the zoom attribute through JS to adjust the zoom ratio to achieve adaptation.

Can vue be adaptive?

The operating environment of this tutorial: Windows 10 system, vue2&&vue3 version, Dell G3 computer.

Can vue be adaptive?

able.

Detailed explanation of the three implementation methods of Vue screen adaptation

Using the scale-box component

Attribute:

  • width Width default1920
  • heightHeight default1080
  • bgcBackground color default "transparent"
  • delayAdaptive scaling anti-shake delay time (ms) Default 100

vue2 Version: vue2 large screen adaptation scaling component (vue2-scale-box - npm)

npm install vue2-scale-box

or

yarn add vue2-scale-box

Usage:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<template>

    <div>

        <scale-box :width="1920" :height="1080" bgc="transparent" :delay="100">

            <router-view />

        </scale-box>

    </div>

</template>

<script>

import ScaleBox from "vue2-scale-box";

export default {

    components: { ScaleBox },

};

</script>

<style lang="scss">

body {

    margin: 0;

    padding: 0;

    background: url("@/assets/bg.jpg");

}

</style>

Copy after login

vue3 version: vue3 large screen Adapt scaling component (vue3-scale-box - npm)

npm install vue3-scale-box

or

yarn add vue3-scale-box

Usage:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<template>

    <ScaleBox :width="1920" :height="1080" bgc="transparent" :delay="100">

        <router-view />

    </ScaleBox>

</template>

<script>

import ScaleBox from "vue3-scale-box";

</script>

<style lang="scss">

body {

    margin: 0;

    padding: 0;

    background: url("@/assets/bg.jpg");

}

</style>

Copy after login

Set the device pixel ratio (device pixel ratio)

In the project Create a new devicePixelRatio.js file under utils

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

class devicePixelRatio {

  /* 获取系统类型 */

  getSystem() {

    const agent = navigator.userAgent.toLowerCase();

    const isMac = /macintosh|mac os x/i.test(navigator.userAgent);

    if (isMac) return false;

    // 目前只针对 win 处理,其它系统暂无该情况,需要则继续在此添加即可

    if (agent.indexOf("windows") >= 0) return true;

  }

  /* 监听方法兼容写法 */

  addHandler(element, type, handler) {

    if (element.addEventListener) {

      element.addEventListener(type, handler, false);

    } else if (element.attachEvent) {

      element.attachEvent("on" + type, handler);

    } else {

      element["on" + type] = handler;

    }

  }

  /* 校正浏览器缩放比例 */

  correct() {

    // 页面devicePixelRatio(设备像素比例)变化后,计算页面body标签zoom修改其大小,来抵消devicePixelRatio带来的变化

    document.getElementsByTagName("body")[0].style.zoom =

      1 / window.devicePixelRatio;

  }

  /* 监听页面缩放 */

  watch() {

    const that = this;

    // 注意: 这个方法是解决全局有两个window.resize

    that.addHandler(window, "resize", function () {

      that.correct(); // 重新校正浏览器缩放比例

    });

  }

  /* 初始化页面比例 */

  init() {

    const that = this;

    // 判断设备,只在 win 系统下校正浏览器缩放比例

    if (that.getSystem()) {

      that.correct(); // 校正浏览器缩放比例

      that.watch(); // 监听页面缩放

    }

  }

}

export default devicePixelRatio;

Copy after login

Introduce and use it in App.vue

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<template>

  <div>

    <router-view />

  </div>

</template>

<script>

import devPixelRatio from "@/utils/devicePixelRatio.js";

export default {

  created() {

    new devPixelRatio().init(); // 初始化页面比例

  },

};

</script>

<style lang="scss">

body {

  margin: 0;

  padding: 0;

}

</style>

Copy after login

Set zoom attribute adjustment through JS Scaling ratio

Create a new monitorZoom.js file under the project's utils

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

export const monitorZoom = () => {

  let ratio = 0,

    screen = window.screen,

    ua = navigator.userAgent.toLowerCase();

  if (window.devicePixelRatio !== undefined) {

    ratio = window.devicePixelRatio;

  } else if (~ua.indexOf("msie")) {

    if (screen.deviceXDPI && screen.logicalXDPI) {

      ratio = screen.deviceXDPI / screen.logicalXDPI;

    }

  } else if (

    window.outerWidth !== undefined &&

    window.innerWidth !== undefined

  ) {

    ratio = window.outerWidth / window.innerWidth;

  }

  if (ratio) {

    ratio = Math.round(ratio * 100);

  }

  return ratio;

};

Copy after login

Introduce and use it in main.js

1

2

3

4

5

6

7

import { monitorZoom } from "@/utils/monitorZoom.js";

const m = monitorZoom();

if (window.screen.width * window.devicePixelRatio >= 3840) {

  document.body.style.zoom = 100 / (Number(m) / 2); // 屏幕为 4k 时

} else {

  document.body.style.zoom = 100 / Number(m);

}

Copy after login

Complete code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

import Vue from "vue";

import App from "./App.vue";

import router from "./router";

/* 调整缩放比例 start */

import { monitorZoom } from "@/utils/monitorZoom.js";

const m = monitorZoom();

if (window.screen.width * window.devicePixelRatio >= 3840) {

  document.body.style.zoom = 100 / (Number(m) / 2); // 屏幕为 4k 时

} else {

  document.body.style.zoom = 100 / Number(m);

}

/* 调整缩放比例 end */

Vue.config.productionTip = false;

new Vue({

  router,

  render: (h) => h(App),

}).$mount("#app");

Copy after login

Get the resolution of the screen

Get the width of the screen:

window.screen.width * window.devicePixelRatio

Get the height of the screen:

window.screen.height * window.devicePixelRatio

Mobile terminal adaptation (use postcss-px-to-viewport plug-in)

Official website:https://www.php.cn/link/2dd6d682870e39d9927b80f8232bd276

npm install postcss-px -to-viewport --save-dev

or

yarn add -D postcss-px-to-viewport

Configuration appropriate Configure the parameters of the plug-in (create a .postcssrc.js file in the project root directory [level with the src directory]) and paste the following code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

module.exports = {

  plugins: {

    autoprefixer: {}, // 用来给不同的浏览器自动添加相应前缀,如-webkit-,-moz-等等

    "postcss-px-to-viewport": {

      unitToConvert: "px", // 需要转换的单位,默认为"px"

      viewportWidth: 390, // UI设计稿的宽度

      unitPrecision: 6, // 转换后的精度,即小数点位数

      propList: ["*"], // 指定转换的css属性的单位,*代表全部css属性的单位都进行转换

      viewportUnit: "vw", // 指定需要转换成的视窗单位,默认vw

      fontViewportUnit: "vw", // 指定字体需要转换成的视窗单位,默认vw

      selectorBlackList: ["wrap"], // 需要忽略的CSS选择器,不会转为视口单位,使用原有的px等单位

      minPixelValue: 1, // 默认值1,小于或等于1px则不进行转换

      mediaQuery: false, // 是否在媒体查询的css代码中也进行转换,默认false

      replace: true, // 是否直接更换属性值,而不添加备用属性

      exclude: [/node_modules/], // 忽略某些文件夹下的文件或特定文件,用正则做目录名匹配,例如 &#39;node_modules&#39; 下的文件

      landscape: false, // 是否处理横屏情况

      landscapeUnit: "vw", // 横屏时使用的视窗单位,默认vw

      landscapeWidth: 2048 // 横屏时使用的视口宽度

    }

  }

};

Copy after login

Recommended learning: "vue. js video tutorial

The above is the detailed content of Can vue be adaptive?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to jump a tag to vue How to jump a tag to vue Apr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

See all articles