搜索
首页web前端前端问答vue能实现自适应吗

vue能实现自适应吗

Dec 30, 2022 pm 03:25 PM
vue自适应

vue能实现自适应,其实现自适应的方法有:1、通过“npm install”或“yarn add”命令安装“scale-box”组件,并使用“scale-box”实现适配缩放;2、通过设置设备像素比例实现自适应;3、通过JS设置zoom属性调整缩放比例来实现自适应即可。

vue能实现自适应吗

本教程操作环境:Windows10系统、vue2&&vue3版、Dell G3电脑。

vue能实现自适应吗?

能。

Vue屏幕自适应三种实现方法详解

使用 scale-box 组件

属性:

  • width宽度 默认1920
  • height高度 默认1080
  • bgc背景颜色 默认"transparent"
  • delay自适应缩放防抖延迟时间(ms) 默认100

vue2版本:vue2大屏适配缩放组件(vue2-scale-box - npm)

npm install vue2-scale-box

或者

yarn add vue2-scale-box

使用方法:

<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>

vue3版本:vue3大屏适配缩放组件(vue3-scale-box - npm)

npm install vue3-scale-box

或者

yarn add vue3-scale-box

使用方法:

<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>

设置设备像素比例(设备像素比)

在项目的 utils 下新建 devicePixelRatio.js 文件

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;

在App.vue 中引入并使用即可

<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>

通过JS设置zoom属性调整缩放比例

在项目的 utils 下新建 monitorZoom.js 文件

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;
};

在main.js 中引入并使用即可

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);
}

完整代码

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");

获取屏幕的分辨率

获取屏幕的宽:

window.screen.width * window.devicePixelRatio

获取屏幕的高:

window.screen.height * window.devicePixelRatio

移动端适配(使用 postcss-px-to-viewport 插件)

官网:https://www.php.cn/link/2dd6d682870e39d9927b80f8232bd276

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

或者

yarn add -D postcss-px-to-viewport

配置适配插件的参数(在项目根目录创建 .postcssrc.js 文件[与 src 目录平级])粘贴以下代码即可

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 // 横屏时使用的视口宽度
    }
  }
};

推荐学习:《vue.js视频教程

以上是vue能实现自适应吗的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
CSS:我可以在同一DOM中使用多个ID吗?CSS:我可以在同一DOM中使用多个ID吗?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

HTML5的目的:创建一个更强大,更容易访问的网络HTML5的目的:创建一个更强大,更容易访问的网络May 14, 2025 am 12:18 AM

html5aimstoenhancewebcapabilities,Makeitmoredynamic,互动,可及可访问。1)ITSupportsMultimediaElementsLikeAnd,消除innewingtheneedtheneedtheneedforplugins.2)SemanticeLelelemeneLementelementsimproveaCceccessibility inmproveAccessibility andcoderabilitile andcoderability.3)emply.3)lighteppoperable popperappoperable -poseive weepivewebappll

HTML5的重要目标:增强网络开发和用户体验HTML5的重要目标:增强网络开发和用户体验May 14, 2025 am 12:18 AM

html5aimstoenhancewebdevelopmentanduserexperiencethroughsemantstructure,多媒体综合和performanceimprovements.1)SemanticeLementLike like,和ImproVereAdiability and ImproVereAdabilityAncccossibility.2)和TagsallowsemplowsemplowseamemelesseamlessallowsemlessemlessemelessmultimedimeDiaiiaemediaiaembedwitWithItWitTplulurugIns.3)

HTML5:安全吗?HTML5:安全吗?May 14, 2025 am 12:15 AM

html5isnotinerysecure,butitsfeaturescanleadtosecurityrisksifmissusedorimproperlyimplempled.1)usethesand andboxattributeIniframestoconoconoconoContoContoContoContoContoconToconToconToconToconToconTedContDedContentContentPrevulnerabilityLikeClickLickLickLickLickLickjAckJackJacking.2)

与较旧的HTML版本相比,HTML5目标与较旧的HTML版本相比,HTML5目标May 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS:使用ID选择器不好吗?CSS:使用ID选择器不好吗?May 13, 2025 am 12:14 AM

使用ID选择器在CSS中并非固有地不好,但应谨慎使用。1)ID选择器适用于唯一元素或JavaScript钩子。2)对于一般样式,应使用类选择器,因为它们更灵活和可维护。通过平衡ID和类的使用,可以实现更robust和efficient的CSS架构。

HTML5:2024年的目标HTML5:2024年的目标May 13, 2025 am 12:13 AM

html5'sgoalsin2024focusonrefinement和optimization,notnewfeatures.1)增强performandemandeffifice throughOptimizedRendering.2)risteccessibilitywithrefinedibilitywithRefineDatientAttributesAndEllements.3)expliencernsandelements.3)explastsecurityConcerns,尤其是withercervion.4)

HTML5试图改进的主要领域是什么?HTML5试图改进的主要领域是什么?May 13, 2025 am 12:12 AM

html5aimedtotoimprovewebdevelopmentInfourKeyAreas:1)多中心供应,2)语义结构,3)formcapabilities.1)offlineandstorageoptions.1)html5intoryements html5introctosements introdements and toctosements and toctosements,简化了inifyingmediaembedingmediabbeddingingandenhangingusexperience.2)newsements.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。