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中, 页面切换的时候,组件销毁的时候执行
// 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 状态
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方法来进行请求操作
// 每次请求可以创建一个新的实例,如果业务不复杂,可以不创建实例,直接使用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去更改状态
}
}
export default homeActions
- 第五步 mutations
// src/store/modules/home/mutations.js
import * as Types from '@/store/action-types'
const homeMutations = {
[Types.SET_CATEGORY](state, payload) { // 修改分类状态
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中的状态绑定到当前的实例
currentCategory: {
get() {
// 取值
return this.category;
},
set(value) {
// 修改状态,默认会调用mutation更改状态
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. 取消请求
当切换页面的时候,之前的请求可以取消掉,因为没有用了
- 定义公共的状态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: { // 公共的状态
tokens: []
},
mutations: {
[Types.SET_TOKEN](state, token) {
// 我们希望状态可以被追踪
state.tokens = [...state.tokens, token] // 存储token,页面切换可以让token依次执行
},
[Types.CLEAR_TOKEN](state) {
state.tokens.forEach(token => token()) // 执行所有的取消方法,都调用一下
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中, 页面切换的时候,组件销毁的时候执行
// 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: '请填写用户名' }]"
/>
<van-field
v-model="password"
type="password"
name="password"
label="密码"
placeholder="密码"
:rules="[{ required: true, message: '请填写密码' }]"
/>
<van-field
v-if="isReg"
v-model="repassword"
type="password"
name="repassword"
label="重复密码"
placeholder="重复密码"
:rules="[{ required: true, message: '请填写密码' }]"
/>
<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'))
}