100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > vue3移动端pc端兼容

vue3移动端pc端兼容

时间:2018-12-29 07:37:25

相关推荐

vue3移动端pc端兼容

1.router文件 index.js配置路由表,把移动端和PC端路由表拆分出来

import { createRouter, createWebHashHistory } from 'vue-router';import { ref, watch } from "vue";/* web */import Home from "views/appWeb/home/Home.vue";// PC端路由const routesPc = [{path: "/",redirect: "/home"},{path: "/home",name: "home",component: Home,}]// 移动端路由表const routesMB = [{path: '/',name: 'home',component: () => import('views/appMobile/home/Home.vue')},]// 声明变量用来接routersvar routes = [];const screenWidth = ref()// 获取页面宽度screenWidth.value = document.body.clientWidthif (screenWidth.value <= 758) {console.log('is Mobile');routes = routesMB} else {routes = routesPc}window.onresize = () => {screenWidth.value = document.body.clientWidth;};// 监听页面宽度watch(screenWidth, (newVal, oldVal) => {let timer = setTimeout(() => {if (newVal <= 758) {// 小于758就是移动端 就把移动端路由表赋给routesconsole.log('is Mobile');routes = routesMBwindow.location.reload()} else {// 大于就是pc端,把pc端路由表赋给routesroutes = routesPcwindow.location.reload()}// 重绘页面}, 500)return () => {// 清除定时器clearTimeout(timer)}}, {// 深度清除deep: true,})const router = createRouter({routes,history: createWebHashHistory()})export default router;

2. appWeb(PC端代码) appMobile(移动端代码)

3.app.vue

<template><div id="app" v-if="isMobile"><h2>这是移动端</h2></div><div id="app" v-else><h2>这是PC端</h2></div></template><script setup>import { onMounted, ref } from "vue";// 判断是pc还是移动端const isMobile = ref(false);const handleResize = () => {isMobile.value = window.matchMedia('(max-width: 768px)').matches;};onMounted(() => {handleResize(); // 初始化时执行一次window.addEventListener('resize', handleResize);// 移动端适配 如果为移动端则执行函数进行适配if (isMobile) {(function (doc, win) {let docEl = doc.documentElement, // 获取htmlresizeEvt = "orientationchange" in window ? "orientationchange" : "resize",width = 750, // 设计稿宽,用时只需要修改这一处recalc = function () {const clientWidth = docEl.clientWidth; // 获取设备尺寸if (!clientWidth) return; // 如果没有值,回去if (clientWidth > width) {// 如果超过设计稿宽度,就给一个固定值docEl.style.fontSize = "100px";// docEl.style.width = width + "px";docEl.style.margin = "0 auto";} else {docEl.style.fontSize = 100 * (clientWidth / width) + "px";docEl.style.width = "";docEl.style.margin = "";}};if (!doc.addEventListener) return; // 如果没有这个方法,中断函数win.addEventListener(resizeEvt, recalc, false); // 改变大小时调整一下doc.addEventListener("DOMContentLoaded", recalc, false); // 加载完成时调整})(document, window);}});</script><style lang="less" scoped>@import 'assets/reset.css';#app{background: #fff;}</style>

4.效果图

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。