五、主题定制
5.1 深色模式
Vant 4支持深色模式,只需在ConfigProvider组件中设置theme="dark"即可。
<template>
<van-config-provider theme="dark">
<!-- 页面内容 -->
<van-button type="primary">按钮</van-button>
</van-config-provider>
</template>
5.2 CSS变量定制
Vant 4使用CSS变量进行主题定制,官方提供了700多个主题变量。
全局定制:
:root {
--van-primary-color: #07c160; /* 主题主色改为绿色 */
--van-border-radius: 8px; /* 圆角大小 */
--van-font-size: 14px; /* 字体大小 */
}
局部定制:
<template>
<div class="custom-theme">
<van-button type="primary">绿色按钮</van-button>
</div>
</template>
<style scoped>
.custom-theme {
--van-primary-color: #07c160;
--van-button-primary-border-radius: 8px;
}
</style>
5.3 动态修改CSS变量
通过JavaScript可以动态修改CSS变量,实现运行时主题切换:
// 切换主题色
const changeThemeColor = (color) => {
document.documentElement.style.setProperty('--van-primary-color', color);
};
// 切换深色模式
const toggleDarkMode = (isDark) => {
if (isDark) {
document.documentElement.style.setProperty('--van-background-color', '#1a1a1a');
document.documentElement.style.setProperty('--van-text-color', '#ffffff');
} else {
document.documentElement.style.setProperty('--van-background-color', '#ffffff');
document.documentElement.style.setProperty('--van-text-color', '#323233');
}
};
六、浏览器适配
6.1 Viewport布局(vw/vh适配)
Vant默认使用px作为样式单位,如果需要使用viewport单位进行移动端适配,推荐使用postcss-px-to-viewport进行转换。
// postcss.config.js
module.exports = {
plugins: {
'postcss-px-to-viewport': {
viewportWidth: 375, // 设计稿宽度
viewportUnit: 'vw', // 转换单位
selectorBlackList: [], // 忽略转换的选择器
minPixelValue: 1, // 最小转换像素值
},
},
};
6.2 Rem布局适配
如果需要使用rem单位进行适配,推荐使用postcss-pxtorem和lib-flexible组合。
// postcss.config.js
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue({ file }) {
// 针对Vant组件使用不同的rootValue
return file.indexOf('vant') !== -1 ? 37.5 : 75;
},
propList: ['*'],
},
},
};
6.3 桌面端适配
Vant默认只监听了移动端的touch事件,如果在桌面端使用Vant,可以引入@vant/touch-emulator将mouse事件转换为touch事件。
npm i @vant/touch-emulator -S
// 引入后自动生效
import '@vant/touch-emulator';
6.4 底部安全区适配
对于iPhone X等带有底部指示条的机型,需要适配安全区。
<!-- 在head标签中添加meta标签 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<template>
<!-- 开启底部安全区适配 -->
<van-number-keyboard safe-area-inset-bottom />
<!-- 开启顶部安全区适配 -->
<van-nav-bar safe-area-inset-top />
</template>
七、性能优化
7.1 按需加载
按需加载是Vant性能优化的核心手段。使用unplugin-vue-components和unplugin-auto-import插件可以实现自动按需加载,打包体积可减少60%以上。
7.2 图标优化
Vant的图标组件支持按需引入,避免全量引入图标库:
<template>
<van-icon name="star-o" />
</template>
<script setup>
// 按需引入图标组件会自动处理,无需额外配置
</script>
7.3 图片懒加载
使用Vant的Lazyload组件实现图片懒加载,优化长列表性能:
<template>
<img v-lazy="imageUrl" />
</template>
<script setup>
import { Lazyload } from 'vant';
// 全局注册
app.use(Lazyload);
</script>
Vant 4作为Vue 3生态中最成熟的移动端组件库,凭借其极致的轻量化、完善的TypeScript支持和丰富的组件生态,已经成为移动端H5开发的首选方案。
来源:
http://uklgy.cn/