中文亚洲精品无码_熟女乱子伦免费_人人超碰人人爱国产_亚洲熟妇女综合网

當(dāng)前位置: 首頁 > news >正文

淄博網(wǎng)站制作高端網(wǎng)絡(luò)登錄百度app

淄博網(wǎng)站制作高端網(wǎng)絡(luò),登錄百度app,wordpress 友情鏈接,wordpress body_classVue Element UI 實(shí)現(xiàn)權(quán)限管理系統(tǒng) 前端篇(三):工具模塊封裝 封裝 axios 模塊 封裝背景 使用axios發(fā)起一個請求是比較簡單的事情,但是axios沒有進(jìn)行封裝復(fù)用,項目越來越大,會引起越來越多的代碼冗余&am…

Vue + Element UI 實(shí)現(xiàn)權(quán)限管理系統(tǒng) 前端篇(三):工具模塊封裝?

封裝 axios 模塊

封裝背景

使用axios發(fā)起一個請求是比較簡單的事情,但是axios沒有進(jìn)行封裝復(fù)用,項目越來越大,會引起越來越多的代碼冗余,讓代碼變得越來越難維護(hù)。所以我們在這里先對 axios 進(jìn)行二次封裝,使項目中各個組件能夠復(fù)用請求,讓代碼變得更容易維護(hù)。

封裝要點(diǎn)

  • 統(tǒng)一 url 配置
  • 統(tǒng)一 api 請求
  • request (請求) 攔截器,例如:帶上token等,設(shè)置請求頭
  • response (響應(yīng)) 攔截器,例如:統(tǒng)一錯誤處理,頁面重定向等
  • 根據(jù)需要,結(jié)合 Vuex 做全局的 loading 動畫,或者錯誤處理
  • 將 axios 封裝成 Vue 插件使用

文件結(jié)構(gòu)

在 src 目錄下,新建一個 http 文件夾,用來存放 http 交互 api 代碼。

config.js:axios 默認(rèn)配置,包含基礎(chǔ)路徑等信息。
axios.js:二次封裝 axios 模塊,包含攔截器等信息。
interface.js?:請求接口匯總模塊,聚合模塊 API。
index.js:將 axios 封裝成插件,按插件方式引入。

config.js

復(fù)制代碼

export default {method: 'get',// 基礎(chǔ)url前綴baseURL: 'http://localhost:8080/',// 請求頭信息headers: {'Content-Type': 'application/json;charset=UTF-8'},// 參數(shù)data: {},// 設(shè)置超時時間timeout: 10000,// 攜帶憑證withCredentials: true,// 返回數(shù)據(jù)類型responseType: 'json'
}

復(fù)制代碼

axios.js

復(fù)制代碼

import axios from 'axios';
import config from './config';
import qs from 'qs';
import Cookies from "js-cookie";
import router from '@/router'// 使用vuex做全局loading時使用
// import store from '@/store'export default function $axios(options) {return new Promise((resolve, reject) => {const instance = axios.create({baseURL: config.baseURL,headers: {},transformResponse: [function (data) {}]})// request 攔截器instance.interceptors.request.use(config => {let token = Cookies.get('token')// 1. 請求開始的時候可以結(jié)合 vuex 開啟全屏 loading 動畫// console.log(store.state.loading)// console.log('準(zhǔn)備發(fā)送請求...')// 2. 帶上tokenif (token) {config.headers.accessToken = token} else {// 重定向到登錄頁面router.push('/login')}// 3. 根據(jù)請求方法,序列化傳來的參數(shù),根據(jù)后端需求是否序列化if (config.method === 'post') {if (config.data.__proto__ === FormData.prototype|| config.url.endsWith('path')|| config.url.endsWith('mark')|| config.url.endsWith('patchs')) {} else {config.data = qs.stringify(config.data)}}return config},error => {// 請求錯誤時console.log('request:', error)// 1. 判斷請求超時if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {console.log('timeout請求超時')// return service.request(originalRequest);// 再重復(fù)請求一次}// 2. 需要重定向到錯誤頁面const errorInfo = error.responseconsole.log(errorInfo)if (errorInfo) {error = errorInfo.data  // 頁面那邊catch的時候就能拿到詳細(xì)的錯誤信息,看最下邊的Promise.rejectconst errorStatus = errorInfo.status; // 404 403 500 ...router.push({path: `/error/${errorStatus}`})}return Promise.reject(error) // 在調(diào)用的那邊可以拿到(catch)你想返回的錯誤信息})// response 攔截器instance.interceptors.response.use(response => {let data;// IE9時response.data是undefined,因此需要使用response.request.responseText(Stringify后的字符串)if (response.data == undefined) {data = JSON.parse(response.request.responseText)} else {data = response.data}// 根據(jù)返回的code值來做不同的處理switch (data.rc) {case 1:console.log(data.desc)break;case 0:store.commit('changeState')// console.log('登錄成功')default:}// 若不是正確的返回code,且已經(jīng)登錄,就拋出錯誤// const err = new Error(data.desc)// err.data = data// err.response = response// throw errreturn data},err => {if (err && err.response) {switch (err.response.status) {case 400:err.message = '請求錯誤'breakcase 401:err.message = '未授權(quán),請登錄'breakcase 403:err.message = '拒絕訪問'breakcase 404:err.message = `請求地址出錯: ${err.response.config.url}`breakcase 408:err.message = '請求超時'breakcase 500:err.message = '服務(wù)器內(nèi)部錯誤'breakcase 501:err.message = '服務(wù)未實(shí)現(xiàn)'breakcase 502:err.message = '網(wǎng)關(guān)錯誤'breakcase 503:err.message = '服務(wù)不可用'breakcase 504:err.message = '網(wǎng)關(guān)超時'breakcase 505:err.message = 'HTTP版本不受支持'breakdefault:}}console.error(err)return Promise.reject(err) // 返回接口返回的錯誤信息})// 請求處理instance(options).then(res => {resolve(res)return false}).catch(error => {reject(error)})})
}

復(fù)制代碼

interface.js

復(fù)制代碼

import axios from './axios'/* * 將所有接口統(tǒng)一起來便于維護(hù)* 如果項目很大可以將 url 獨(dú)立成文件,接口分成不同的模塊*/// 單獨(dú)導(dǎo)出
export const login = () => {return axios({url: '/login',method: 'get'})
}export const getUser = () => {return axios({url: '/user',method: 'get'})
}export const getMenu = data => {return axios({url: '/menu',method: 'post',data})
}// 默認(rèn)全部導(dǎo)出
export default {login,getUser,getMenu
}

復(fù)制代碼

index.js

復(fù)制代碼

// 導(dǎo)入所有接口
import apis from './interface'const install = Vue => {if (install.installed)return;install.installed = true;Object.defineProperties(Vue.prototype, {// 注意,此處掛載在 Vue 原型的 $api 對象上$api: {get() {return apis}}})
}export default install

復(fù)制代碼

安裝 js-cookie

上面 axios.js 中,會用到 Cookie 獲取 token,所以需要把相關(guān)依賴安裝一下。

執(zhí)行以下命令,安裝依賴包。

yarn add js-cookie

代碼實(shí)例

1.引入插件

在 main.js 中以 vue 插件的形式引入 axios,這樣在其他地方就可通過?this.$api 調(diào)用相關(guān)的接口了。

2.編寫接口

在 interface.js 中添加 login 接口。

3.調(diào)用接口

在登錄界面 Login.vue 中,添加一個登錄按鈕,點(diǎn)擊處理函數(shù)通過 axios 調(diào)用 login 接口返回數(shù)據(jù)。

成功返回之后,將 token 放入 Cookie 并跳轉(zhuǎn)到主頁。

復(fù)制代碼

<template><div class="page"><h2>Login Page</h2><el-button type="primary" @click="login()">登錄</el-button></div>
</template><script>import mock from '@/mock/mock.js';import Cookies from "js-cookie";import router from '@/router'export default {name: 'Login',methods: {login() {this.$api.login().then(function(res) {alert(res.data.token)Cookies.set('token', res.data.token) // 放置token到Cookie router.push('/')  // 登錄成功,跳轉(zhuǎn)到主頁}).catch(function(res) {alert(res);});}}}
</script>

復(fù)制代碼

4.mock 接口

在 mock.js 中添加 login 接口進(jìn)行攔截,返回一個 token。

啟動測試

瀏覽器訪問:http://localhost:8080/#/login,顯示登錄界面。

點(diǎn)擊登錄按鈕,首先彈出框,顯示返回的 token 信息。

點(diǎn)擊確定關(guān)掉彈出框后,跳轉(zhuǎn)到主頁。點(diǎn)擊用戶、菜單按鈕,接口調(diào)用正常。

封裝 mock 模塊

為了統(tǒng)一可以統(tǒng)一管理和集中控制數(shù)據(jù)模擬接口,我們對 mock 模塊進(jìn)行了封裝,可以方便的定制模擬接口的統(tǒng)一開關(guān)和個體開關(guān)。

文件結(jié)構(gòu)

在 mock 目錄下新建一個 index.js ,創(chuàng)建 modules 目錄并在里面創(chuàng)建三個模塊 *.js 文件。

index.js:模擬接口模塊聚合文件

login.js:登錄相關(guān)的接口模擬

user.js:用戶相關(guān)的接口模擬

menu.js:菜單相關(guān)的接口模擬

index.js

復(fù)制代碼

import Mock from 'mockjs'
import * as login from './modules/login'
import * as user from './modules/user'
import * as menu from './modules/menu'// 1. 開啟/關(guān)閉[業(yè)務(wù)模塊]攔截, 通過調(diào)用fnCreate方法[isOpen參數(shù)]設(shè)置.
// 2. 開啟/關(guān)閉[業(yè)務(wù)模塊中某個請求]攔截, 通過函數(shù)返回對象中的[isOpen屬性]設(shè)置.
fnCreate(login, true)
fnCreate(user, true)
fnCreate(menu, true)/*** 創(chuàng)建mock模擬數(shù)據(jù)* @param {*} mod 模塊* @param {*} isOpen 是否開啟?*/
function fnCreate (mod, isOpen = true) {if (isOpen) {for (var key in mod) {((res) => {if (res.isOpen !== false) {Mock.mock(new RegExp(res.url), res.type, (opts) => {opts['data'] = opts.body ? JSON.parse(opts.body) : nulldelete opts.bodyconsole.log('\n')console.log('%cmock攔截, 請求: ', 'color:blue', opts)console.log('%cmock攔截, 響應(yīng): ', 'color:blue', res.data)return res.data})}})(mod[key]() || {})}}
}

復(fù)制代碼

login.js

復(fù)制代碼

// 登錄接口
export function login () {return {// isOpen: false,url: 'http://localhost:8080/login',type: 'get',data: {'msg': 'success','code': 0,'data': {'token': '4344323121398'// 其他數(shù)據(jù)}}}
}

復(fù)制代碼

user.js

復(fù)制代碼

// 獲取用戶信息
export function getUser () {return {// isOpen: false,url: 'http://localhost:8080/user',type: 'get',data: {'msg': 'success','code': 0,'data': {'id': '@increment', 'name': '@name', // 隨機(jī)生成姓名'email': '@email', // 隨機(jī)生成姓名'age|10-20': 12// 其他數(shù)據(jù)}}}
}

復(fù)制代碼

menu.js

復(fù)制代碼

// 獲取菜單信息
export function getMenu () {return {// isOpen: false,url: 'http://localhost:8080/menu',type: 'get',data: {'msg': 'success','code': 0,'data': {'id': '@increment', 'name': 'menu', // 隨機(jī)生成姓名'order|10-20': 12// 其他數(shù)據(jù)}}}
}

復(fù)制代碼

修改引入

Login.vue

Home.vue

啟動測試

瀏覽器訪問:http://localhost:8080/#/,按照先前流程走一遍,沒有問題。

http://www.risenshineclean.com/news/58846.html

相關(guān)文章:

  • 溫州做網(wǎng)站建設(shè)公司百度sem
  • 在線商城網(wǎng)站開發(fā)代碼windows優(yōu)化大師是病毒嗎
  • 建立網(wǎng)站平臺需要那些技術(shù)鎮(zhèn)江seo快速排名
  • 正能量網(wǎng)站ip網(wǎng)絡(luò)營銷推廣有哪些方法
  • 網(wǎng)站設(shè)計 聯(lián)系怎樣進(jìn)行網(wǎng)絡(luò)推廣效果更好
  • 做網(wǎng)站需要網(wǎng)站負(fù)責(zé)人推動防控措施持續(xù)優(yōu)化
  • 提卡的網(wǎng)站怎么做查網(wǎng)站權(quán)重
  • 123邢臺招聘信息網(wǎng)鄭州企業(yè)網(wǎng)站seo
  • 微信開發(fā)網(wǎng)站建設(shè)天津網(wǎng)站優(yōu)化
  • 網(wǎng)站建設(shè)調(diào)查問卷天津網(wǎng)絡(luò)廣告公司
  • 如何做php分頁網(wǎng)站seo查詢愛站
  • 織夢做的網(wǎng)站后臺頁優(yōu)化軟件
  • 專做壞消息的網(wǎng)站南寧seo產(chǎn)品優(yōu)化服務(wù)
  • 網(wǎng)站建設(shè)學(xué)院廣州網(wǎng)站建設(shè)公司
  • 網(wǎng)站建設(shè)哪個公司的好進(jìn)入百度知道首頁
  • 怎么用 c文件做網(wǎng)站頁面關(guān)鍵詞優(yōu)化
  • 企業(yè)網(wǎng)站建設(shè)方案書范文浙江新手網(wǎng)絡(luò)推廣
  • 做頭像網(wǎng)站長沙網(wǎng)紅打卡景點(diǎn)排行榜
  • 無錫制作網(wǎng)站公司賣友情鏈接的哪來那么多網(wǎng)站
  • wordpress做的網(wǎng)站嗎整站seo外包
  • 外貿(mào)專業(yè)網(wǎng)站的公司江西網(wǎng)絡(luò)推廣seo
  • 廣州知名網(wǎng)站建設(shè)后臺管理便捷淘寶店鋪如何推廣
  • 中山 網(wǎng)站制作重慶seo優(yōu)化
  • 邯鄲網(wǎng)站建設(shè)公司哪家好建站軟件可以不通過網(wǎng)絡(luò)建設(shè)嗎
  • 怎么樣分析一個網(wǎng)站百度搜索引擎seo
  • b2b電子商務(wù)網(wǎng)站開發(fā)在線排名優(yōu)化工具
  • 公司官網(wǎng)定制上海網(wǎng)站排名seo公司哪家好
  • ui設(shè)計是什么職位aso優(yōu)化是什么
  • 怎么修改網(wǎng)站源文件十大基本營銷方式
  • 零食網(wǎng)站制作的建設(shè)大綱域名查詢138ip