喜报喜报!!!!!!今年最后三十分钟的上班时间,事情不多写下这篇文章
最近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
})()
}
},
以上就是所有代码和逻辑了,各位朋友有任何问题请私信我或者评论区留言!!!!