Vue PC端和移动端适配样式(css样式)

项目需求:XX项目时间赶,主做PC端,移动端是在原有基础上改动,

在这一基础上,建议直接采用@media 媒体查询大小屏幕进行css调整,通过window.screen.width判断屏幕宽度
在这里插入图片描述
在这里插入图片描述

一、需要一个全局globalMixin.js,判断当前屏幕为移动端还是PC端
export const GlobalMixin = {
	data() {
	    return {
	        isApp: false // true:代表移动端,false:代表PC端
	    }
	},
	created() {
		/** 先判断平台,pc端 or 移动端*/
        this.whichPlatform()
	},
	methods: {
        /** PC端、移动端 判断*/
        whichPlatform() {
            if(window.screen.width < 800) {
                this.isApp = true
            }else {
                this.isApp = false
            }
        }
    }
}
二、在.vue文件中mixins混入globalMixin.js,直接根据 isApp变量修改样式

可以通过 :class:style 改变当前样式,也可根据 @media媒体查询来修改样式

<template>
	<div :class="isApp ? 'red' : 'blue'">
		小屏幕背景颜色为红色,大屏幕背景为蓝色 (可以通过F12检查代码,切换大小屏幕,感受变化)
	</div>
	<div :style="{height: isApp ? '100px' : '300px'}">
		小屏幕最小高度为100px,大屏幕高度为300px (可以通过F12检查代码,切换大小屏幕,感受变化)
	</div>
	<div class="box">
		小屏幕宽度为50%,大屏幕宽度为100% (可以通过F12检查代码,切换大小屏幕,感受变化)
	</div>
	<div class="platform_pc">PC端)改行文字在PC端展示,在移动端消失
	</div>
	<div class="platform_app">
		(移动端)改行文字在移动端展示,在PC端消失
	</div>
</template>
<script>
	import { GlobalMixin } from '@/mixins/globalMixin'
    export default {
        name: 'XXX',
        mixins:[GlobalMixin],
    }
</script>
<style>
	.red{ background: red;}
	.blue{ background: blue;}
	.box{ width: 100%}
//媒体查询 自适应
//PC端
@media screen and (min-width:800px){
  .platform_pc{
    display: block;
  }
  .platform_app{
    display: none;
  }
}
//移动端
@media screen and (max-width:700px){
  .platform_pc{
    display: none;
  }
  .platform_app{
    display: block;
    max-width: 100%;
  }
  .box{ width: 50%;}
}
</style>

版权声明:本文为sunshineTing2原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。