移动端与pc端不同,需要更多的考虑em,rem的单位转化,各个手机型号完美适配。对新手而言,这是一个难点。接下来我将以一个外卖移动端为例子进行讲解。
目录
一、屏幕的适配插件
1、安装
-
postcss-pxtorem
:这个插件的作用是将CSS中的像素单位(px)转换为相对于根元素字体大小的rem单位。这样做的好处是,它可以帮助开发者创建响应式设计,使得在不同设备上显示的元素大小可以根据屏幕大小进行缩放。 amfe-flexible
:这个插件是阿里巴巴的一个前端团队开发的,它的作用是让移动端页面的尺寸单位统一为rem,并且可以方便地在不同设备上进行适配。它通过修改根元素的font-size来实现这一点。
npm i postcss-pxtorem@5.1.1 amfe-flexible -S
2、vite.config.js
配置
postcssPxtorem()
:这是调用postcss-pxtorem
插件的地方。rootValue: 16
:这个选项指定了根元素(html元素)的字体大小,这里设置为16px。这意味着1rem等于16px。propList: ["*"]
:这个选项指定了需要转换为rem单位的CSS属性列表。这里使用["*"]
表示所有属性都将被转换。
import { defineConfig } from 'vite';
import postcssPxtorem from 'postcss-pxtorem';
export default defineConfig({
css: {
postcss: {
plugins: [
postcssPxtorem({
rootValue: 16,
propList: ["*"],
}),
],
},
},
// 其他配置...
});
3、引入amfe-flexible,实现伸缩布局
在你的项目的入口文件(通常是index.js
或main.js
)中引入amfe-flexible
:
import 'amfe-flexible';
这行代码会将amfe-flexible
的样式应用到你的整个项目中。
这样你的移动端页面在检查时拖拽,大小宽高就会跟着变化啦!
二、预编译器
less-loader
是一个 webpack 模块加载器,用于将 LESS 文件编译成 CSS。
pnpm i less-loader@7 -S
三、pinia实现购物车功能
购物车没有商品时
购物车有商品时
点击购物车图标会显示购物清单
我们不难发现,商品总个数,单个个数,单价,总价,需要在多个组件中用到,所以我们把它们存到Pinia仓库中集中管理。
1、商品总数
Pinia仓库的搭建与安装不多赘述。购物车上方的小红点即是点击+号就会增加的商品总数。
total属性初始为0,每点击+号就会调用increment()方法给 total 加1
// stores/cart.js
import { defineStore } from "pinia";
export const useCartStore = defineStore("cart", {
state: () => ({
total: 0,
}),
actions: {
// 总个数
increment() {
this.total++;
},
},
});
<van-button size="mini" @click="incrementCart(item)">+</van-button>
<script setup>
const cartStore = useCartStore(); // 使用 Pinia 仓库
const incrementCart = (item) => {
cartStore.increment(); // 更新 Pinia 仓库
};
</script>
2、单个商品个数增加
在仓库中创建cartItems存储被点击的项和价格
{ ...item, count: 1 } 如果item中没有count属性,则添加,如果有则覆盖。
export const useCartStore = defineStore("cart", {
state: () => ({
cartItems: [], // 存储每个商品的点击次数和价格
}),
actions: {
// 商品添加的列表
addCartItem(item) {
const existingIndex = this.cartItems.findIndex(
(cartItem) => cartItem.id === item.id
);
if (existingIndex !== -1) {
// 如果商品已存在,则增加点击次数
this.cartItems[existingIndex].count++;
this.total++;
} else {
// 如果商品不存在,则添加到数组中,点击次数为1
this.cartItems.push({ ...item, count: 1 });
}
},
},
});
3、单个商品个数减少
和个数增加的逻辑差不多,但需要判断count为0时移除列表。
// 商品减少的列表
removeCartItem(item) {
const existingIndex = this.cartItems.findIndex(
(cartItem) => cartItem.id === item.id
);
if (existingIndex !== -1) {
// 如果商品已存在,则减少点击次数
this.cartItems[existingIndex].count--;
this.total--;
if (this.cartItems[existingIndex].count === 0) {
// 如果点击次数为0,则从数组中移除该商品
this.cartItems.splice(existingIndex, 1);
}
}
},
4、总价
在仓库中创建totalAmount存储总价,初始为0。
// 计算总价
recalculateTotalAmount() {
this.totalAmount = this.cartItems.reduce((sum, cartItem) => {
return sum + cartItem.price * cartItem.count;
}, 0);
},
5、清空购物车
// 清空购物车
clearCart() {
this.cartItems = [];
this.total = 0;
this.totalAmount = 0;
},
在组件中调用仓库绑定仓库中的点击事件就可以啦~
配套后台管理系统实现请移步本人另一篇: