在下面环节会讲解怎么做pc和移动端网页样式适配。
在当下有两种实现样式适配的:JS 适配方案和CSS 媒体查询适配。下面会具体讲解一下代码该怎么写。
🙏 希望该文章能帮助到你。
比如在src/router/index.vue文件中有一个统一的Layout组件包裹,可以在Layout组件内部通过当前界面尺寸监听来判断当前是PC还是移动端。 可以新建一个mixin类文件ResizeHandler.js,内容如下:
const { body } = document
const WIDTH = 992
export default {
beforeMount() {
window.addEventListener('resize', this.$_resizeHandler)
},
beforeDestroy() {
window.removeEventListener('resize', this.$_resizeHandler)
},
mounted() {
const isMobile = this.$_isMobile()
// 做相应的逻辑处理,控制哪些显示哪些不显示?怎么显示?等
},
methods: {
$_isMobile() {
const rect = body.getBoundingClientRect()
return rect.width - 1 < WIDTH
},
$_resizeHandler() {
if (!document.hidden) {
const isMobile = this.$_isMobile()
store.dispatch('app/toggleDevice', isMobile ? 'mobile' : 'desktop')
// 做相应的逻辑处理,控制哪些显示哪些不显示?怎么显示?等
}
}
}
}
然后在Layout组件中使用: