vue는 자체 적응을 달성하는 방법은 다음과 같습니다: 1. "npm install" 또는 "yarn add" 명령을 통해 "scale-box" 구성 요소를 설치하고 "scale-box"를 사용하여 달성합니다. 2. 장치 픽셀 비율을 설정하여 자체 적응을 실현합니다. 3. JS를 통해 확대/축소 속성을 설정하여 자체 적응을 달성합니다.
이 튜토리얼의 운영 환경: Windows 10 시스템, vue2&&vue3 버전, Dell G3 컴퓨터.
vue가 적응형일 수 있나요?
예.
Vue 화면 적응의 세 가지 구현 방법에 대한 자세한 설명
scale-box 구성 요소 사용
속성:
-
width
너비 기본값은1920
width
宽度 默认1920
-
height
高度 默认1080
-
bgc
背景颜色 默认"transparent"
-
delay
自适应缩放防抖延迟时间(ms) 默认100
height
높이 기본값은 1080
bgc
배경색 기본값은 "투명"
지연
적응형 스케일링 흔들림 방지 지연 시간(ms) 기본 100
vue2 버전:
vue2 대형 화면 적응 스케일링 구성 요소(vue2-scale-box - npm)
npm install 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또는
<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>장치 픽셀 비율(장치 픽셀 비율)을 설정하세요프로젝트 아래에 새 devicePixelRatio를 만듭니다. utils.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를 통해 확대/축소 속성을 설정하여 확대/축소 비율을 조정프로젝트의 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; };메인에서 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또는
적응 플러그인의 매개변수 구성(프로젝트 루트 디렉터리 .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/], // 忽略某些文件夹下的文件或特定文件,用正则做目录名匹配,例如 'node_modules' 下的文件 landscape: false, // 是否处理横屏情况 landscapeUnit: "vw", // 横屏时使用的视窗单位,默认vw landscapeWidth: 2048 // 横屏时使用的视口宽度 } } };🎜🎜권장 학습: "🎜vue.js 비디오 튜토리얼🎜 "🎜
위 내용은 vue는 적응형이 될 수 있나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

usestate () isareacthookusedtomanagestatefunctionalcomponents.1) itinitializesandupdatesstate, 2) workaledtthetThetThepleFcomponents, 3) canleadto'Stalestate'ifnotusedCorrecrally 및 4) performancanoptimizedUsecandusecaldates.

Reactispopularduetoitscomponent 기반 아카데입, 가상, Richcosystem 및 declarativenature.1) 구성 요소 기반 ectureallowsforeusableuipieces, Modularityandmainability 개선 가능성.

TodebugreactApplicationseffective, UsetheseStradegies : 1) 주소 propdrillingwithContapiorredux.2) handleaSnchronousOperationswithUsestAndUseefect, abortControllerTopReceConditions.3) 최적화 formanceSeMoAnduseCalbackTooid

usestate () inreactAllowsStateManagementInfunctionalComponents.1) itsimplifiessTatemanagement, 2) usethepRevCountFunctionToupDatesTestateSpreviousValue, PropeingStaleScallanceBackferperperperperperperperperperperperperpertoptiMizatio

chelectionSimple, IndependentStateVaribles; useUserEducer () useuserEducer () forcomplexStateLogicor () whenStatedSonpreviousState.1) usestate () isidealforsimpleupdatesliketogglingabooleorupdatingacounter.2) usbetterformanagingmentiplesub-vvalusorac

Usestate는 클래스 구성 요소 및 기타 상태 관리 솔루션보다 우수합니다. 국가 관리를 단순화하고 코드를 더 명확하게하고 읽기 쉽고 React의 선언적 특성과 일치하기 때문입니다. 1) Usestate는 함수 구성 요소에서 상태 변수를 직접 선포 할 수있게합니다. 2) 후크 메커니즘을 통해 다시 렌더링하는 동안 상태를 기억합니다.

useUsestate () forlocalcomponentStateManagement; 고려 사항 forglobalstate, complexlogic, orperformanceissues.1) usestate () isidealforsimple, localstate.2) useglobalstatesolutionslikereduxorcontextforsharedstate.3) optforredooxtoolkitormobxcomcoccomcoccomcoccomcoccomcoccomcoccomcoccomcoccomporccomcoccomporccomcoccomport

reusablecomponentsinreacececodemainabenabilityandefficiency는 hallowingesamecomponentacrossdifferentpartsofanapplicationorprojects.1) 그들을 retuduceredundancyandsimplifyupdates.2) theyseconsistencyinuserexperience.3) theyquireoptim


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는
