目录
一、项目准备
二、基础语法应用
2.1、mixin应用
2.2、网络请求
2.3、显示与隐藏
2.4、编程式路由跳转
2.5、下载资料
2.6、调用方法
2.7、监听路由变化
2.8、pinia应用
(1)存储token(user.js)
(2)全选全不选案例(car.js)
下载:
cnpm i unplugin-auto-import -D //setup 语法糖插件
npm i -D @types/node //解决vite不能@问题
npm install element-plus --save //组件库
npm install -D unplugin-vue-components //按需引入组件库
npm install less
npm install less-loader
npm install @originjs/vite-plugin-global-style
在vite.config.js中
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import globalStyle from '@originjs/vite-plugin-global-style'
// cnpm i unplugin-auto-import -D setup 语法糖插件
import AutoImport from 'unplugin-auto-import/vite'
import path from 'path'
export default defineConfig({
plugins: [vue(),
AutoImport({
imports: ['vue', 'vue-router']
}),
globalStyle({
sourcePath:'./src/assets/css',
lessEnabled:true
}),
],
resolve: {
// 配置路径别名(解决vite不能@问题) npm i -D @types/node
alias: {
"@": path.join(__dirname, 'src'),
"#": path.join(__dirname, 'types')
}
}
})
组件库地址: 设计 | Element Plus
在v-for循环的时候,后端返回的状态是数字,而前端需要将它回显成对应的汉字,可以使用mixin将这快封装起来。
import courseType from "../../mixins/courseType.js";
let { courseTypeFn } = courseType();
mixin文件夹下的js代码:
export default function () {
let courseTypeFn = (type) => {
let val = ''
switch (type) {
case 1:
val = '初级';
break;
case 2:
val = '中级';
break;
case 3:
val = '高级';
break;
default:
val = ''
}
return val;
}
return { courseTypeFn, }
}
视图应用:{{ courseTypeFn(item.courseLevel) }}
methods里面也可以判断状态:
拿到请求后,先定义数据类型,在onBeforeMount生命周期里面去获取数据。
// api
import {
getSliders,
getFirstCategorys,
} from "@/api/api.js";
import { onBeforeMount } from "vue";
// 轮播图数据
let sliderList = ref([]);
// 一级分类数据
let firstList = ref([]);
// 生命周期
onBeforeMount(() => {
getSliders().then((res) => {
sliderList.value = res.data.list;
});
getFirstCategorys().then((res) => {
firstList.value = res.data.list;
});
});
// 定义数据
let isShow = ref(false);
// 事件
const mouseHover = () => {
isShow.value = true;
);
};
import { useRouter } from "vue-router";
const router = useRouter();
//方法里跳转指定页面
const GoJump = (id) => {
router.push({
path: "/about/details",
query: { id },
});
};
接收参数
import { useRoute } from "vue-router";
let route = useRoute();
courseId: route.query.id,
获取后端返回的文件流,自己组装出一个文件全称,在页面创建a标签,实现下载功能。
const download = (item) => {
downloadAttachment({
courseId: item.courseId,
attachmentId: item.id,
}).then((res) => {
//后端返回的是文件流
const blob = new Blob([res]);
let fileName = item.attachmentName;
let fileUrl = item.attachmentUrl;
const extName = fileUrl.substring(fileUrl.lastIndexOf(".")); //.gif
fileName = fileName + extName; //kkkk.gif
// 前端创建a标签进行新窗口的打开
const link = document.createElement("a");
link.download = fileName;
link.target = "_black";
link.style.display = "none";
link.href = URL.createObjectURL(blob);
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href);
document.body.removeChild(link);
});
};
或者可以直接 window.open(info.url);
const pageSize = ref(8);
const getlist = () => {
mostNew({
pageNum: pageNum.value,
pageSize: pageSize.value,
}).then((res) => {
newList.value = res.data.pageInfo.list;
total.value = res.data.pageInfo.total;
});
};
const handleSizeChange = (val) => {
pageSize.value = val;
getlist();
};
// 头部监听路由变化
watch(
() => router.currentRoute.value.name,
(toPath) => {
if (toPath == "Home") {
currentId.value = 1;
} else if (toPath == "About") {
currentId.value = 2;
} else if (toPath == "Shop") {
currentId.value = 3;
}
},
{ immediate: true }
);
下载持久化存储插件:cnpm i pinia-plugin-persist
文件夹的index.js
import {createPinia} from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
const store=createPinia()
store.use(piniaPluginPersist)
export default store
import { defineStore } from 'pinia'
export const useUserStore = defineStore({
id: 'user',
state: () => {
return {
token: ''
}
},
actions: {
setToken(token) {
this.token = token
}
},
// 开启数据缓存
persist: {
enabled: true,
strategies: [{
key: 'xiao_user',
storage: localStorage
}]
}
})
页面使用:
// pinia
import { useUserStore } from "../stores/user.js";
const userStore = useUserStore();
userStore.setToken(res.data.accessToken);
解构
import { defineStore } from 'pinia'
export const useCartStore = defineStore({
id: 'cart',
state: () => {
return {
cartList: [],//购物车数量
select: [],//选中的商品id
}
},
getters: {
isChecked() {
return this.select.length == this.cartList.length
}
},
actions: {
addCart(list) {
list.forEach(v => {
v['check'] = true
this.select.push(v.id)
})
this.cartList = list
},
// 全选
all() {
this.select = this.cartList.map(v => {
v['check'] = true
return v.id
})
},
// 全不选
unAll() {
this.cartList.forEach(v => {
v['check'] = false
})
this.select = []
},
//单个选
itemChecked(index) {
let id = this.cartList[index].id;
let idx = this.select.indexOf(id);//检查它里面有没有
if (idx > -1) {
this.cartList[index].check = false;
this.select.splice(idx, 1);//有
} else {
this.cartList[index].check = true;
this.select.push(id);//没有
}
}
},
})
页面使用:
import { storeToRefs } from "pinia";
import { useCartStore } from "../stores/car.js";
let cartStore = useCartStore();
let { cartList, isChecked } = storeToRefs(cartStore);
onBeforeMount(() => {
getShopCarList().then((res) => {
firstList.value = res.data.list;
});
cartStore.addCart(firstList.value);
console.log(cartStore.cartList);
});
const checkAll = () => {
if (isChecked.value) {
cartStore.unAll(); // 不选
} else {
cartStore.all(); // 全选
}
};