上一章讲了怎么安装vuex并且应用 这一章我们安装使用并且封装axios,在前端中数据交互可以说是非常频繁,所以一个项目必须得使用axios在得到后端传递的数据
1,安装axios,npm install axios --save
2,配置开发环境和生产环境,因为在实际开发过程中我们开发的baseUrl往往是后端的ip+port,打包上线都是https://…。需要在根目录新建文件.env.development和.env.production,名字别写错了。然后变量以VITE开头大写
# development
VITE_BASE_URL='http://192.168.3.67:9088/api'
# production
VITE_BASE_URL='https://.......api'
然后记得重启
获取环境变量是import.meta.env.VITE_BASE_URL
3,在src下新建utils文件夹,utils下面新建request.js文件,封装一下axios
import axios from 'axios'
const service = axios.create({
baseURL: import.meta.env.VITE_BASE_URL,
timeout: 5000
})
service.interceptors.request.use(config => {
config.headers = {
"Authorization": 'your token',
'Content-Type': "application/json;charset=utf-8"
}
return config
}, error => {
Promise.reject(error)
})
service.interceptors.response.use(res => {
const code = res.data.code || 200;
if (code == 200) {
return res
} else {
return Promise.reject('error')
}
},
error => {
return Promise.reject(error)
}
)
function post(url, params) {
return new Promise((resolve, reject) => {
service.post(url, params).then(
(response) => {
resolve(response.data)
},
(err) => {
reject(err)
}
)
})
}
function get(url, params = {}) {
return new Promise((resolve, reject) => {
service.get(url, { params: params }).then((response) => {
resolve(response.data)
})
.catch((err) => {
reject(err)
})
})
}
function put(url, params = {}) {
return new Promise((resolve, reject) => {
service.put(url, params).then(
(response) => {
resolve(response.data)
},
(err) => {
reject(err)
}
)
})
}
function remove(url, data) {
return new Promise((resolve, reject) => {
service
.delete(url, { data })
.then((response) => {
resolve(response.data)
})
.catch((err) => {
reject(err)
})
})
}
export default {
get,
post,
put,
remove,
}
4,然后在src下面新建api文件夹,然后具体的接口就可以在这里写,页面中引用哪个模块的接口导入就好了,以用户为例(当然这个目录结构看具体项目,个人习惯写在系统目录中)
目录结构大概是这样的
import request from '@/utils/request'
export function getUserInfo(params) {
return request.get('/api-user/users/current', params)
}
5,我们稍微对之前博客写的改一下路由结构和页面信息,使得页面更清晰
<script setup></script>
<template>
<router-view></router-view>
</template>
<style></style>
之前没有说到路由钩子,我们这边可以利用路由前置做一些判断或者设置,这在项目中经常用到,保持vue2的写法
import { createRouter, createWebHistory } from "vue-router"
const routes = [
{
path: '/',
name: 'home',
meta:{
title:"首页"
},
component: () => import('@/view/home.vue')
},
{
path: '/user',
name: 'user',
meta:{
title:"个人中心"
},
component: () => import('@/view/user.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
router.beforeEach((to, from, next) => {
document.title = to.meta.title
next()
})
export default router
<script setup></script>
<template>
欢迎来到首页<br />
<router-link to="/user">去个人中心</router-link>
</template>
<style></style>
<script setup>
import { reactive, computed } from "vue";
import { useStore } from "vuex";
const store = useStore();
const userInfo = reactive({
username: "",
phone: "",
});
const age = computed(() => store.state.user.age);
function add() {
store.commit("add");
}
</script>
<template>
<h1>用户名:{{ userInfo.username }}</h1>
<h2>联系方式:{{ userInfo.phone }}</h2>
<h4>{{ age }}</h4>
<button @click="add">年纪+1</button>
<br /><br />
<router-link to="/">返回首页</router-link>
</template>
<style></style>
6,调用接口,在页面中使用axios渲染数据
<script setup>
import { reactive, computed } from "vue";
import { useStore } from "vuex";
import { getUserInfo } from "@/api/system/user.js";
const store = useStore();
const age = computed(() => store.state.user.age);
const userInfo = reactive({
username: "",
phone: "",
});
function add() {
store.commit("add");
}
function receiveUserInfo() {
getUserInfo().then((res) => {
userInfo.username = res.data.username;
userInfo.phone = res.data.phone;
});
}
receiveUserInfo();
</script>
<template>
<h1>用户名:{{ userInfo.username }}</h1>
<h2>联系方式:{{ userInfo.phone }}</h2>
<h4>{{ age }}</h4>
<button @click="add">年纪+1</button>
<br /><br />
<router-link to="/">返回首页</router-link>
</template>
<style></style>
页面效果如图所示 至于为什么可以直接调用,这和vue3的生命周期有关,以后会接着讲
这样就好了,欢迎留言
|