vue3使用自定义指令实现页面自适应

以往做自适应布局时通常使用媒体查询,接下来讲解如何用通过自定义指令实现
官方文档介绍:

自定义指令 | Vue3中文文档 - vuejs

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为其他端样式

这样就实现了用自定义指令实现自适应页面 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在uni-app中,可以通过自定义指令实现适应DPR加载图片。具体步骤如下: 1. 在项目的`main.js`中注册自定义指令: ```javascript import Vue from 'vue'; import App from './App'; Vue.config.productionTip = false; // 注册自定义指令 Vue.directive('adapt-img', { bind: function (el, binding) { let dpr = window.devicePixelRatio; let value = binding.value; if (value) { if (dpr >= 3 && value.indexOf('@3x') !== -1) { el.setAttribute('src', value.replace('@3x', '')); } else if (dpr >= 2 && value.indexOf('@2x') !== -1) { el.setAttribute('src', value.replace('@2x', '')); } else { el.setAttribute('src', value); } } }, }); App.mpType = 'app'; const app = new Vue({ ...App, }); app.$mount(); ``` 这里注册了一个名为`adapt-img`的自定义指令,当该指令绑定到元素上时,会根据当前设备的DPR加载对应的图片。 2. 在需要使用适应DPR加载图片的地方,将自定义指令`adapt-img`绑定到`<img>`标签上,并设置图片路径: ```html <template> <div class="demo"> <img v-adapt-img src="@/static/img/[email protected]" /> </div> </template> <style> .demo img { width: 100px; height: 100px; } </style> ``` 这里将自定义指令`adapt-img`绑定到`<img>`标签上,并设置图片路径为`@/static/img/[email protected]`。在绑定指令时,可以将图片路径作为指令的值传递过去。 3. 在图片文件夹中,只需要提供@2x和@3x倍图即可,不需要提供@1x倍图。 这样,当页面加载时,自定义指令会根据当前设备的DPR加载对应的图片,如果当前设备的DPR为1,则会加载原始图片。 需要注意的是,如果图片文件名中包含了`@2x`或`@3x`,需要在指令中进行判断并替换。如果图片文件名中没有包含`@2x`或`@3x`,则直接加载原始图片。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值