日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

vue项目封装axios

發布時間:2023/12/31 vue 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vue项目封装axios 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

先看一下 我們的結構:


第一階段 配置:

api文件夾說明
api文件夾存放接口

user.js

import request from "../utils/request";//保存游戲類型 export function saveGame(data) {return request({url: "/user-setting/xxxx",method: "post",data}); }//獲取游戲類型 export function getGame(data) {return request({url: "/user-setting/xxxxx",method: "get",data}); }

這里我們引入了,utils文件夾下的request.js

utils文件夾說明*
utils文件夾存放工具文件

request.js


首先需要安裝axios,和qs,以及 ant-design-vue(也可以別的UI庫 或者 不是使用也行)

import axios from "axios"; import qs from "qs"; import { getToken } from "../utils/auth"; import Message from "ant-design-vue/es/message";// create an axios instance const service = axios.create({baseURL: process.env.VUE_APP_BASE_API,withCredentials: true,timeout: 5000,headers: {"Content-Type": "application/x-www-form-urlencoded"} });// 請求攔截 service.interceptors.request.use(config => {// do something before request is sentif (config.method === "post" || config.method === "put") {config.data = qs.stringify(config.data);}if (config.method === "get") {config.url = config.url + "?" + qs.stringify(config.data);}// if (store.getters.token) {// let each request carry token// ['X-Token'] is a custom headers key// please modify it according to the actual situation// config.headers['X-Token'] = getToken()// Cookie: APPMGRID=5dcf8572f7c74ee28309b3ff67063686if (getToken()) {config.headers["token"] = getToken(); //這里換成你的token名字}// }return config;},error => {// do something with request errorconsole.log(error);return Promise.reject(error);} );// 響應攔截 service.interceptors.response.use(response => {const data = response.data;switch (data.code) {case 0:return Promise.resolve(data);case 301:Message.warn(data.msg || "請先登錄");break;case 400:Message.warn(data.message || res.data.msg || "資源不在收藏列表中");break;case 401:Message.error(data.msg || "請先登錄");break;case 403:Message.error(data.msg || "權限不足");break;case 404:Message.error(data.msg || "請求資源不存在");break;case 408:Message.error(data.message || "已經收藏過該視頻");break;case 500:Message.error(data.msg || "服務器開小差啦");break;case 504:Message.error(data.msg || "網絡請求失敗");break;default:Message.error(data.msg || "請求失敗");}},error => {console.log("err" + error);// Message({// message: error.message,// type: 'error',// duration: 5 * 1000// })return Promise.reject(error);} );export default service;

上述代碼引入了,getToken ,這里主要是auth.js 中設置的,主要作用是在 完成登錄后,后面的請求 都在頭部添加上token。


auth.js
需要安裝 js-cookie

import Cookies from "js-cookie";const TokenKey = "token"; //這里是你的token名 const UseridKey = "USERID";export function getToken() {return Cookies.get(TokenKey); }export function setToken(token) {return Cookies.set(TokenKey, token); }export function removeToken() {return Cookies.remove(TokenKey); }export function getUserid() {return Cookies.get(UseridKey); }export function setUserid(Userid) {return Cookies.set(UseridKey, Userid); }export function removeUserid() {return Cookies.remove(UseridKey); }

第二階段 使用:

store主要用于數據處理:

index.js

import Vue from "vue"; import Vuex from "vuex"; import state from "./state"; import mutations from "./mutations"; import getters from "./getters"; import user from './modules/user'; //用戶信息 import app from './modules/app'; //離線數據庫Vue.use(Vuex);export default new Vuex.Store({state,getters,mutations,modules:{user:user,app:app} });

user.js

import {saveGame,getGame, } from "../../api/user.js";let state = {gameType: "",userInfos: "" }; let getters = {userId: state =>(Object.keys(state.userInfo).length > 0 && state.userInfo.profile.userId) ||"",userPlaylists: state => state.userPlaylists,createdList: state => {return state.userPlaylists.filter(item => {return !item.subscribed;});},likedPlaylistIds: state => state.userPlaylists.map(item => item.id),likedsongIds: state => state.likedsongIds };let mutations = {SET_USER_INFOS(state, data) {state.userInfos = data.data;},SET_GAME_TYPE(state, data) {state.gameType = data;} };let actions = {GET_USER_INFO({ commit }, data) {getGame({}).then(data => {commit("SET_USER_INFOS", data);});},CHOOSE_GAME({ commit }, data) {let postData = {game_abbr: data};saveGame(postData).then(data => {commit("SET_GAME_TYPE", data);});} };export default {namespaced: true,state,getters,mutations,actions };

在項目中使用,例如這里的的保存游戲,去調用一個接口:

當單機確定的時候,去發送請求

choose_game.vue

<template><div class="choose-game"><div class="m-t"><div class="header">請選擇您常用的游戲</div><div class="determine"><a href="#" class="animBtn themeA" @click="close">確定</a></div></div></div> </template><script> import { mapState, mapMutations, mapActions } from "vuex"; export default {name: "ChooseGame",data() {return {choose: false,type: "csgo"};},methods: {...mapActions("user", ["CHOOSE_GAME"]), //調引入mapActions 里面的接口close() {this.showDial = false;this.CHOOSE_GAME(this.type).then(rev => {}); //調用接口}} }; </script>

第三階段 配置環境:

這里有兩種環境,開發 和生產環境

.env.development

# just a flag ENV = 'development'# base api VUE_APP_BASE_API = 'https://test/xxxxxxx.csgo.com/' # vue-cli uses the VUE_CLI_BABEL_TRANSPILE_MODULES environment variable, # to control whether the babel-plugin-dynamic-import-node plugin is enabled. # It only does one thing by converting all import() to require(). # This configuration can significantly increase the speed of hot updates, # when you have a large number of pages. # Detail: https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/babel-preset-app/index.jsVUE_CLI_BABEL_TRANSPILE_MODULES = true

.env.production

# just a flag ENV = 'production'# base api #VUE_APP_BASE_API = '/prod-api' VUE_APP_BASE_API = 'https://xxxxxxx.csgo.com/'

總結

以上是生活随笔為你收集整理的vue项目封装axios的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。