pc端移动端相互切自动换跳转(全网最简单最全方法)

文章介绍了如何在Vue2和Vue3项目中,利用屏幕尺寸变化来实现在PC和移动端间的自动跳转,避免了复杂的浏览器内核判断。作者提供了详细的代码示例,包括使用`ref`和`watch`在移动端和PC端之间的切换逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

喜报喜报!!!!!!今年最后三十分钟的上班时间,事情不多写下这篇文章

最近pm提的一个功能。最开始在网上找了很多方法,很多都是判断浏览器内核或者uniapp的api判断移动端设备信息进行跳转,出现了一些问了,于是自己着手写了一个简单粗暴的方法,直接监听页面尺寸进行跳转,而且pc切换成移动端或者移动端切换成pc端能自动进行跳转,不需要手动去刷新

话不多说,开讲了  ps:由于我做的项目pc端和移动端的app.vue文件里面一个是v2的写法一个是v3的写法,所以下面我会将vue2和vue3的写法都展示出来,所以很全。

pc(vue3)

import { skipUrl } from "@/utils/auth.js";
let screenWidth = ref(document.body.clientWidth);
onMounted(() => {
  window.onreset = () => {
    return () => {
      screenWidth.value = document.body.clientWidth;
    };
  };
  window.addEventListener("resize", getWindowInfo);
});
const getWindowInfo = () => {
  const windowInfo = {
    width: window.innerWidth,
    hight: window.innerHeight,
  };
  // 屏幕尺寸小于700(移动端)
  if (windowInfo.width < 700) {
    if (window.location.href.includes(skipUrl().h5_url)) return;
    window.location.href = skipUrl().h5_url;
  }
  // 屏幕尺寸大于700(pc端)
  if (windowInfo.width >= 700) {
    if (window.location.href.includes(skipUrl().pc_url)) return;
    window.location.href = skipUrl().pc_url;    
  }
};

auth.js文件里面的代码,这里我只写了一个简单的判断,开年后会更新一版全一点的(过年闲的话也可以hhhhhhhhhh)

// 切换多端跳转地址
export const skipUrl = () => {
  // 本地跳转
  if (window.location.href.includes("localhost")) {
    const url = {
      h5_url: window.location.href,
      pc_url: window.location.href,
    };
    // const url = {
    //   h5_url: "http://localhost:5173/",
    //   pc_url: "http://localhost:3000/",
    // };
    return url;
  } else {
    const url = {
      h5_url: "http://********************/",
      pc_url: "http://********************/",
    };
    // 线上跳转  
    return url;
  }
};

移动端(vue2)

data() {
	return {
		screenWidth: document.body.clientWidth
	}
},
watch: {
	screenWidth: {
		handler(newVal, oldVal) {
			if (newVal < 700) {
				if (window.location.href.includes(skipUrl().h5_url)) return;
                window.location.href = skipUrl().h5_url;
			}
			if (newVal >= 700) {
				if (window.location.href.includes(skipUrl().pc_url)) return;
                window.location.href = skipUrl().pc_url;  
			}
		},
		immediate: true,
		deep: true
    }
},
mounted() {
	window.onresize = () => {
		return (() => {
			this.screenWidth = document.body.clientWidth
		})()
	}
},

以上就是所有代码和逻辑了,各位朋友有任何问题请私信我或者评论区留言!!!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

 冰紫露恋蝶玛丽红红秃头宝贝

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值