以往做自适应布局时通常使用媒体查询,接下来讲解如何用通过自定义指令实现
官方文档介绍:
1、先获取屏幕宽高等信息
export function getSystemInfo() {
let screenFix = /^Apple/.test(navigator.vendor) && typeof window.orientation === 'number'
let landscape = screenFix && Math.abs(window.orientation) === 90
let screenWidth = screenFix ? Math[landscape ? 'max' : 'min'](screen.width, screen.height) : screen.width
let screenHeight = screenFix ? Math[landscape ? 'min' : 'max'](screen.height, screen.width) : screen.height
let windowWidth = Math.min(window.innerWidth, document.documentElement.clientWidth, screenWidth) || screenWidth
let windowHeight = window.innerHeight ;
return { windowWidth , windowHeight , screenWidth , screenHeight };
}
2、创建directive.js ,在该文件中创建自定义指令
let { windowWidth } = getSystemInfo();
export function media(dom, binding) {
if (windowWidth > 768) return;
let value = binding.value;
let arg = binding.arg;
let className = dom.className;
if (!!className && className.indexOf(value) > -1) return;
if (arg == 'append') value += ` ${dom.className}`;
dom.setAttribute('class', value);
}
3、在index.js中注册指令,注册好后在页面中就可以使用v-media=''''指令
//注册指令
app.directive('media', media);
4、页面中使用,如图class为web端样式,v-media为其他端样式
这样就实现了用自定义指令实现自适应页面