在下面环节会讲解怎么做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
组件中使用: