1. axios封裝
// src/utils/axios.js
import axios from 'axios'
class HttpRequest {
constructor() {
// 接口地址(根據實際情況修改)
this.baseURL = process.env.NODE_ENV === 'production' ? '/' : 'http://localhost:7001'
this.timeout = 3000
// loading 需要加 (一般項目不加判呕,在組件中加)
this.queue = {} // 專門用來維護請求隊列的压昼,做loading處理的
// 頁面切換 需要取消請求
}
setInterceptor(instance, url) {
instance.interceptors.request.use((config) => {
// 開啟loading 一個頁面多個請求,只產生一個loading
if (Object.keys(this.queue).length === 0) {
// 開loading
}
// 可以記錄請求的取消函數
let CancelToken = axios.CancelToken
config.cancelToken = new CancelToken((c) => { // 存到vuex中钧大, 頁面切換的時候翰撑,組件銷毀的時候執(zhí)行
// c 就是當前取消請求的token
console.log(c)
})
this.queue[url] = true
return config // 返回配置文件,請求的時候要用
})
// 攔截器
instance.interceptors.response.use((res) => {
delete this.queue[url] // 一旦響應了 就從隊列刪除
if (Object.keys(this.queue).length === 0) { // 如果隊列有值
// close loading
}
if (res.data.err === 0) { // 根據實際接口調整 可swithCase 狀態(tài)
return res.data.data
} else {
return Promise.reject(res.data) // 失敗拋出異常
}
}, (err) => {
delete this.queue[url]
if (Object.keys(this.queue).length === 0) { // 如果隊列有值
// close loading
}
return Promise.reject(err)
})
}
request(options) { // 通過 request方法來進行請求操作
// 每次請求可以創(chuàng)建一個新的實例啊央,如果業(yè)務不復雜眶诈,可以不創(chuàng)建實例,直接使用axios
let instance = axios.create()
let config = {
baseURL: this.baseURL,
timeout: this.timeout,
...options
}
this.setInterceptor(instance, config.url)
return instance(config) // 產生的是一個 promise
}
get(url, data = {}) {
return this.request({
url,
method: 'get',
...data
})
}
post(url, data = {}) {
return this.request({
url,
method: 'post',
data
})
}
}
export default new HttpRequest
2. 請求輪播圖數據劣挫,并存到vuex中
- vuex流程第一步 state 定義變量
// src/store/modules/home/state.js
const homeState = {
category: -1,
slides: [], // 接口返回的輪播圖數據
}
export default homeState
- 第二步 action-types 維護所有的動作
// src/store/action-types.js
// 所有的名字都列在這里
// 首頁
export const SET_CATEGORY = 'SET_CATEGORY'
// 輪播圖
export const SET_SLIDES = 'SET_SLIDES'
- 第三步 api
// src/api/home.js
import axios from '@/utils/axios'
// 設置接口 自己根據實際接口修改
export const fecthSlides = () => axios.get('/api/slider')
// 該接口返回數據:
// { err: 0,
// data: [
// {url: "http://www.xxx"},
// {url: "http://www.xxx"}
// ]
// }
- 第四步 actions 異步請求
// src/store/modules/home/actions.js
import * as Types from '@/store/action-types'
import { fecthSlides } from '@/api/home.js'
const homeActions = {
async [Types.SET_SLIDES]({ commit }) {
let slides = await fecthSlides()
commit(Types.SET_SLIDES, slides) // 交給mutation去更改狀態(tài)
}
}
export default homeActions
- 第五步 mutations
// src/store/modules/home/mutations.js
import * as Types from '@/store/action-types'
const homeMutations = {
[Types.SET_CATEGORY](state, payload) { // 修改分類狀態(tài)
state.category = payload
},
[Types.SET_SLIDES](state, slides) {
state.slides = slides // 更新輪播圖數據
}
}
export default homeMutations
- 組件應用
// src/views/home/index.vue
<template>
<div>
<!-- v-model 相當于 :value="value" @input="change" -->
<HomeHeader v-model="currentCategory"></HomeHeader>
<van-swipe class="my-swipe" :autoplay="2000" indicator-color="white">
<van-swipe-item v-for="(s, index) in slides" :key="index">
<img :src="s.url" alt="" />
</van-swipe-item>
</van-swipe>
</div>
</template>
<script>
import HomeHeader from "./home-header.vue";
import { createNamespacedHelpers } from "vuex";
import * as Types from "@/store/action-types";
// 這里拿到的是 home 模塊下的
let {
mapState: mapHomeState,
mapMutations,
mapActions,
} = createNamespacedHelpers("home");
export default {
methods: {
...mapMutations([Types.SET_CATEGORY]),
...mapActions([Types.SET_SLIDES]),
},
mounted() {
if (this.slides.length === 0) {
// 如果vuex沒有數據才請求,有數據直接用
this[Types.SET_SLIDES]();
}
},
computed: {
...mapHomeState(["category", "slides"]), // 獲取vuex中的狀態(tài)綁定到當前的實例
currentCategory: {
get() {
// 取值
return this.category;
},
set(value) {
// 修改狀態(tài)东帅,默認會調用mutation更改狀態(tài)
this[Types.SET_CATEGORY](value);
},
},
},
components: {
HomeHeader,
},
data() {
return {
value: -1, // 全部 -1, node 0, react 1, vue 2
};
},
};
</script>
<style lang="scss">
.my-swipe {
height: 120px;
img {
height: 100%;
width: 100%;
}
}
</style>
3. 取消請求
當切換頁面的時候压固,之前的請求可以取消掉,因為沒有用了
- 定義公共的狀態(tài)tokens
// src/store/index.js
import Vue from "vue";
import Vuex from "vuex";
import modules from './modules/index.js'
import * as Types from '@/store/action-types'
Vue.use(Vuex);
const store = new Vuex.Store({
state: { // 公共的狀態(tài)
tokens: []
},
mutations: {
[Types.SET_TOKEN](state, token) {
// 我們希望狀態(tài)可以被追蹤
state.tokens = [...state.tokens, token] // 存儲token靠闭,頁面切換可以讓token依次執(zhí)行
},
[Types.CLEAR_TOKEN](state) {
state.tokens.forEach(token => token()) // 執(zhí)行所有的取消方法帐我,都調用一下
state.tokens = [] // 清空列表
}
},
actions: {},
modules: {
...modules
},
});
export default store
- 設置token
// src/store/action-types.js
export const SET_TOKEN = 'SET_TOKEN'
export const CLEAR_TOKEN = 'CLEAR_TOKEN'
- 修改 axios
// src/utils/axios.js
import store from '../store'
import * as Types from '@/store/action-types'
instance.interceptors.request.use((config) => {
// 開啟loading 一個頁面多個請求,只產生一個loading
if (Object.keys(this.queue).length === 0) {
// 開loading
}
// 可以記錄請求的取消函數
let CancelToken = axios.CancelToken
// 相當于 xhr.abort() 中斷請求的方法
config.cancelToken = new CancelToken((c) => { // 存到vuex中愧膀, 頁面切換的時候拦键,組件銷毀的時候執(zhí)行
// c 就是當前取消請求的token
store.commit(Types.SET_TOKEN, c) // 同步將取消方法存入到vuex中
})
this.queue[url] = true
return config // 返回配置文件,請求的時候要用
})
- 路由鉤子封裝檩淋,取消請求
// src/router/hooks.js
import store from "../store"
import * as Types from '@/store/action-types'
export default {
// 'clear_token' 這個只是給自己看的芬为,沒有任何實際意義
'clear_token': (to, from, next) => {
// whiteList 可以添加一些白名單萄金,不清空
store.commit(Types.CLEAR_TOKEN) // 清空 token
next()
}
}
// src/router/index.js
import hooks from './hooks'
Object.values(hooks).forEach(hook => {
router.beforeEach(hook)
})
4. 繪制頁面
- 登錄、注冊公共組件
// src/components/form-submit.vue
<template>
<div>
<van-form @submit="onSubmit">
<van-field
v-model="username"
name="username"
label="用戶名"
placeholder="用戶名"
:rules="[{ required: true, message: '請?zhí)顚懹脩裘? }]"
/>
<van-field
v-model="password"
type="password"
name="password"
label="密碼"
placeholder="密碼"
:rules="[{ required: true, message: '請?zhí)顚懨艽a' }]"
/>
<van-field
v-if="isReg"
v-model="repassword"
type="password"
name="repassword"
label="重復密碼"
placeholder="重復密碼"
:rules="[{ required: true, message: '請?zhí)顚懨艽a' }]"
/>
<div style="margin: 16px" v-if="isLogin">
<van-button round block type="info" native-type="submit"
>登錄</van-button
>
<br />
<van-button round block to="/reg" type="primary">去注冊</van-button>
</div>
<div style="margin: 16px" v-if="isReg">
<van-button round block native-type="submit" type="info"
>注冊</van-button
>
</div>
</van-form>
</div>
</template>
<script >
export default {
data() {
return {
username: "",
password: "",
repassword: "",
};
},
computed: {
isLogin() {
return this.$route.path === "/login";
},
isReg() {
return this.$route.path === "/reg";
},
},
methods: {
onSubmit(values) {
this.$emit("submit", values);
},
},
};
</script>
- 個人中心
// src/views/profile/index.vue
<template>
<div class="profile">
<van-nav-bar title="個人中心"></van-nav-bar>
<div class="profile-info">
<template v-if="true">
<img src="@/assets/logo.png" />
<van-button size="small" to="/login">登錄</van-button>
</template>
<template v-else>
<!-- 頭像上傳 -->
<img src="@/assets/logo.png" />
<span>張三</span>
</template>
</div>
</div>
</template>
<style lang="scss">
.profile {
.profile-info {
display: flex;
align-items: center;
height: 150px;
padding: 0 15px;
img {
width: 100px;
height: 100px;
}
}
}
</style>
- 登錄頁面
// src/views/login/index.vue
<template>
<div>
<van-nav-bar
title="登錄"
left-arrow
@click-left="$router.back()"
></van-nav-bar>
<FormSubmit @submit="submit"></FormSubmit>
</div>
</template>
<script >
import FormSubmit from "@/components/form-submit";
export default {
components: {
FormSubmit,
},
methods: {
submit(values) {
console.log(values);
},
},
};
</script>
- 注冊頁面
// src/views/reg/index.vue
<template>
<div>
<van-nav-bar
title="注冊"
left-arrow
@click-left="$router.back()"
></van-nav-bar>
<FormSubmit @submit="submit"></FormSubmit>
</div>
</template>
<script >
import FormSubmit from "@/components/form-submit";
export default {
components: {
FormSubmit,
},
methods: {
submit(values) {
console.log(values);
},
},
};
</script>
- 路由配置
// src/router/index.js 新增下面路由
{
path: '/login',
name: 'login',
component: loadable(() => import('@/views/login/index.vue'))
},
{
path: '/reg',
name: 'reg',
component: loadable(() => import('@/views/reg/index.vue'))
}