目錄
一、項(xiàng)目準(zhǔn)備
二、基礎(chǔ)語法應(yīng)用
2.1、mixin應(yīng)用
2.2、網(wǎng)絡(luò)請求
2.3、顯示與隱藏
2.4、編程式路由跳轉(zhuǎn)
2.5、下載資料
2.6、調(diào)用方法
2.7、監(jiān)聽路由變化
2.8、pinia應(yīng)用
(1)存儲token(user.js)
(2)全選全不選案例(car.js)
一、項(xiàng)目準(zhǔn)備
下載:
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')
}
}
})
組件庫地址:?設(shè)計(jì) | Element Plus
二、基礎(chǔ)語法應(yīng)用
2.1、mixin應(yīng)用
在v-for循環(huán)的時(shí)候,后端返回的狀態(tài)是數(shù)字,而前端需要將它回顯成對應(yīng)的漢字,可以使用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, }
}
視圖應(yīng)用:{{ courseTypeFn(item.courseLevel) }}
methods里面也可以判斷狀態(tài):
2.2、網(wǎng)絡(luò)請求
拿到請求后,先定義數(shù)據(jù)類型,在onBeforeMount生命周期里面去獲取數(shù)據(jù)。
// api
import {
getSliders,
getFirstCategorys,
} from "@/api/api.js";
import { onBeforeMount } from "vue";
// 輪播圖數(shù)據(jù)
let sliderList = ref([]);
// 一級分類數(shù)據(jù)
let firstList = ref([]);
// 生命周期
onBeforeMount(() => {
getSliders().then((res) => {
sliderList.value = res.data.list;
});
getFirstCategorys().then((res) => {
firstList.value = res.data.list;
});
});
2.3、顯示與隱藏
<div class="active-r" v-if="isShow"></div>
// 定義數(shù)據(jù)
let isShow = ref(false);
// 事件
const mouseHover = () => {
isShow.value = true;
);
};
2.4、編程式路由跳轉(zhuǎn)
import { useRouter } from "vue-router";
const router = useRouter();
//方法里跳轉(zhuǎn)指定頁面
const GoJump = (id) => {
router.push({
path: "/about/details",
query: { id },
});
};
接收參數(shù)
import { useRoute } from "vue-router";
let route = useRoute();
courseId: route.query.id,
2.5、下載資料
獲取后端返回的文件流,自己組裝出一個(gè)文件全稱,在頁面創(chuàng)建a標(biāo)簽,實(shí)現(xiàn)下載功能。
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
// 前端創(chuàng)建a標(biāo)簽進(jìn)行新窗口的打開
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);
2.6、調(diào)用方法
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();
};
2.7、監(jiān)聽路由變化
// 頭部監(jiān)聽路由變化
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 }
);
2.8、pinia應(yīng)用
下載持久化存儲插件: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
(1)存儲token(user.js)
import { defineStore } from 'pinia'
export const useUserStore = defineStore({
id: 'user',
state: () => {
return {
token: ''
}
},
actions: {
setToken(token) {
this.token = token
}
},
// 開啟數(shù)據(jù)緩存
persist: {
enabled: true,
strategies: [{
key: 'xiao_user',
storage: localStorage
}]
}
})
頁面使用:
// pinia
import { useUserStore } from "../stores/user.js";
const userStore = useUserStore();
userStore.setToken(res.data.accessToken);
(2)全選全不選案例(car.js)
解構(gòu)文章來源:http://www.zghlxwxcb.cn/news/detail-671197.html
import { defineStore } from 'pinia'
export const useCartStore = defineStore({
id: 'cart',
state: () => {
return {
cartList: [],//購物車數(shù)量
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 = []
},
//單個(gè)選
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);//沒有
}
}
},
})
頁面使用:文章來源地址http://www.zghlxwxcb.cn/news/detail-671197.html
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(); // 全選
}
};
到了這里,關(guān)于Vue3項(xiàng)目實(shí)戰(zhàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!