nuxt3+pinia+elementplus+fetch請求封裝
1.集成
npm i?@vueuse/nuxt --save?
npm i?sass --save
npm i?sass-loader --save
npm i?element-plus --save
npm i?@element-plus/nuxt --save
npm i?@element-plus/icons-vue --save? 圖標
npm i pinia --save?
npm i?@pinia/nuxt --save
npm i?@pinia-plugin-persistedstate/nuxt --save? ? ?持久化插件
nuxt.config.ts? 配置文件如下:
export default defineNuxtConfig({
? vite: {
? ? css: {
? ? ? preprocessorOptions: {
? ? ? ? scss: {
? ? ? ? ? additionalData: '@use "@/assets/styles/index.scss" as *;', // 這里是你自己的scss樣式文件
? ? ? ? },
? ? ? },
? ? },
? ? server: { fs: { strict: false } },
? },
? modules: [
? ? "@vueuse/nuxt",
? ? "@pinia/nuxt",
? ? "@pinia-plugin-persistedstate/nuxt",
? ? "@element-plus/nuxt",
? ],
? vueuse: {
? ? ssrHandlers: true,
? },
? elementPlus: {?
? ? icon: "ElIcon", // icon前綴?<el-icon><el-icon-close /></el-icon>
? },
});
pinia配置:
在composables目錄下創(chuàng)建stores.ts:
import { defineStore } from "pinia";
export const useUserStore = defineStore("user-info", {
? state: (): any => ({
? ? user: null,
? }),
? actions: {
? ? async login(data: any) {
? ? ? this.user = data;
? ? ? setStorage("user", data);
? ? },
? ? async logout() {
? ? ? this.user = null;
? ? ? removeStorage("user");
? ? },
? },
? persist: true, // 持久化
});
直接在vue文件使用:
const userStore = useUserStore();
console.log(userStore.user);
fetch封裝配置:
在composables目錄下創(chuàng)建useMyFetch.ts:
import { ElMessage } from "element-plus";
import config from "~~/config";
const fetch = $fetch.create({
? // 請求攔截器
? async onRequest({ options }) {
? ? options.baseURL = config.baseurl;
? ? // 添加請求頭,沒登錄不攜帶token
? ? const userStore = useUserStore();
? ? const userInfo = userStore.user;
? ? if (!userInfo) return;
? ? options.headers = new Headers(options.headers);
? ? options.headers.set("token", `${userInfo.token}`);
? },
? // 響應攔截
? onResponse({ response }) {
? ? const userStore = useUserStore();
? ? let data = response._data;
? ? if (data.code != 200) {
? ? ? ElMessage.error(data.message);
? ? ? if (data.message == "請先登錄!") {
? ? ? ? userStore.logout();
? ? ? }
? ? }
? ? if (response.headers.get("content-disposition") && response.status === 200)
? ? ? return response;
? ? // 在這里判斷錯誤
? ? if (response._data.code !== 200) return Promise.resolve(response._data);
? ? // 成功返回
? ? return response._data;
? },
? // 錯誤處理
? onResponseError(error) {
? ? const err = (text: string) => {
? ? ? ElMessage.error(error?.response?._data.message ?? text);
? ? };
? ? if (error?.response?._data) {
? ? ? switch (error.response.status) {
? ? ? ? case 404:
? ? ? ? ? err("服務器資源不存在");
? ? ? ? ? break;
? ? ? ? case 500:
? ? ? ? ? err("服務器內部錯誤");
? ? ? ? ? break;
? ? ? ? case 401:
? ? ? ? ? // 清除緩存
? ? ? ? ? err("登錄狀態(tài)已過期,需要重新登錄");
? ? ? ? ? // TODO 跳轉到登錄界面
? ? ? ? ? break;
? ? ? ? case 403:
? ? ? ? ? err("沒有權限訪問該資源");
? ? ? ? ? break;
? ? ? ? default:
? ? ? ? ? err("未知錯誤!");
? ? ? }
? ? } else {
? ? ? err("請求超時,服務器無響應!");
? ? }
? ? return Promise.reject(error?.response?._data ?? null);
? },
});
// 自動導出
export const useHttp = {
? get: (url: string, params?: any) => {
? ? return fetch(url, { method: "get", params });
? },
? post: (url: string, params?: any) => {
? ? return fetch(url, { method: "post", body: params });
? },
};
使用:
?useHttp.post("/answer/addAnswer", {
? ? ...option,
? });
useHttp.get("/common/getQiniuToken", {
? ? ...option,
?});
好了到這里基本就配置完成了 其他的不懂可以
官網: https://www.nuxtjs.org.cn/
nuxt3交流: qun?702247654