1.定义一个requset.js    名字有语义

/**
 * axios 封装
 */

import axios from 'axios'
import storage from './storage'
const TOKEN_INVALID = 'Token认真失败,请重新认证'
const NETWORK_ERROR = '网络异常,请稍后重试'

const service = axios.create({
    timeout: 8000
})


service.interceptors.request.use((req) => {
    const headers = req.headers
    const {token} = storage.getItem('userInfo')
    if (!headers.Authorization) headers.Authorization = 'Bearer '+token
    return req
})

service.interceptors.response.use((res) => {
    const {code, data, msg} = res.data
    if (code === 200) {
        return data
    } else if (code === 50001) {
        this.$message.error(TOKEN_INVALID)
        setTimeout(() => {
            this.$router.push('/login')
        }, 15000)
        return Promise.reject(TOKEN_INVALID)
    } else {
        this.$message.error(msg || NETWORK_ERROR)
        return Promise.reject(msg || NETWORK_ERROR)
    }
},err => {
    this.$message.error(msg || NETWORK_ERROR)
    return Promise.reject(msg || NETWORK_ERROR)
})


/**
 * 
 * @param {*} options 请求的配置
 * @returns 
 */
function request(options) {
    options.method = options.method || 'get'
    if (options.method.toLowerCase() === 'get') {
        options.params = options.data
    }
    return service(options)
}


export default request

2.定义api 管理  index.js  统一管理请求

/**
 * api  管理
 */
import request from '../utils/request'

export default {
    Login (params) {
       return request({
            url: '/api/users/login',
            method: 'post',
            data: params
        })
    },
    getUerList (params) {
        return request({
            url: '/test/users/list',
            method: 'get',
            data: params
        })
    },
    handleDel (params) {
        return request({
            url: '/test/users/delete',
            method: 'post',
            data: params
        })
    },
    getDeptIdList () {
        return request({
            url: '/test/dept/list',
            method: 'get',
            data: {}
        })
    },
    getRolesList () {
        return request({
            url: '/test/roles/allList',
            method: 'get',
            data: {}
        })
    },
    handleSubmit (params) {
        return request({
            url: '/test/users/operate',
            method: 'post',
            data: params
        })
    },
    heandlePatchDel (params) {
        return request({
            url: '/test/users/delete',
            method: 'post',
            data: params
        })
    },
    handleDel (params) {
        return request({
            url: '/test/users/delete',
            method: 'post',
            data: params
        })
    },
}

3. storage  封装   config.namesp  就是一个字符串

import config from '../config'
export default {
    setItem (key, value) {
        let storage = this.getStorage()
        storage[key] = value
        window.localStorage.setItem(config.namespace,JSON.stringify(storage))
    },
    getItem (key) {
        return this.getStorage()[key]
    },
    clearItem (key) {
        let storage = this.getStorage()
        delete storage[key]
        window.localStorage.setItem(config.namespace,JSON.stringify(storage))
    },
    clearAll () {
        window.localStorage.clear()
    },
    getStorage () {
        return JSON.parse(window.localStorage.getItem(config.namespace) || "{}")
    }
}

4.统一api 调用

<script>
export default {
    name: 'user',
    data () {
        return {
            showModel: false,
            user: {
                state: 0
            },
            pager: {
                pageNum: 1,
                pageSize: 10,
                total: 10
            },
            userList: [],
            checkUserIds: [], // 选择用户列表对象
            columns: [
                {
                label: '用户ID',
                prop: 'userId',
            },
            {
                label: '用户名称',
                prop: 'userName',
            },
            {
                label: '用户邮箱',
                prop: 'userEmail',
            },
            {
                label: '用户角色',
                prop: 'role',
                formatter (row, column, value) {
                    return {
                        0: '管理员',
                        1: '普通用户'
                    }[value]
                }
            },
            {
                label: '用户状态',
                prop: 'state',
                formatter (row, column, value) {
                    return {
                        1: '在职',
                        2: '离职',
                        3: '试用期'
                    }[value]
                }
            },
            {
                label: '注册时间',
                prop: 'createTime',
            },
            {
                label: '最后登录时间',
                prop: 'lastLoginTime',
            }
            ],
            userForm: {
                state: 3
            },
            rules: {
                userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
                userEmail: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
                mobile: [
                        {
                            pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
                            message: '请输入正确格式的手机号', 
                            trigger: 'blur' 
                        }
                ]
            },
            roleList: [], //角色列表
            deptList: [], //部门列表
            action: 'add'
        }
    },
    mounted () {
        this.getUerList()
        this.getDeptIdList()
        this.getRolesList()
    },
    methods: {
        async getUerList () {
            let params = {}
            Object.assign(params,this.user,this.pager)
        //    this.$axios.get('/test/users/list', {
        //        params
        //    }).then(res => {
        //        this.userList = res.list
        //        this.pager.total = res.page.total
        //    })
        const res = await this.$api.getUerList(params)
        if (res) {
            this.userList = res.list
            this.pager.total = res.page.total
        }
        console.log(res);
        },
        handleReset(form) {
            this.$refs[form].resetFields()
        },
        heandleQuery () {
            this.getUerList()
        },
        handleCurrentChange (current) {
            this.pager.pageNum = current
            this.getUerList()
        },
        async handleDel (row) { // 用户单个删除
            // this.$axios.post('/test/users/delete', {
            //     data: {
            //         userIds: [row.userId]
            //     }
            // }).then(() => {
            //     this.$message.success('删除成功')
            //     this.getUerList()
            // })
            const res = await this.$api.handleDel({userIds: [row.userId]})
            if (res) {
                this.$message.success('删除成功')
                this.getUerList()
            }
        },
       async heandlePatchDel () {
            if (this.checkUserIds.length === 0) {
                this.$message.error('请选择要删除的用户')
                return
            }
            // this.$axios.post('/test/users/delete', {
            //     data: {
            //         userIds: this.checkUserIds
            //     }
            // }).then((res) => {
            //     if (res.nModified > 0) {                  
            //         this.$message.success('删除成功')
            //         this.getUerList()
            //     } else {
            //         this.$message.success('删除失败')
            //     }
            // })
            const res = await this.$api.heandlePatchDel({userIds: this.checkUserId})
            if (res) {
                if (res.nModified > 0) {
                    this.$message.success('删除成功')
                    this.getUerList()
                } else {
                    this.$message.success('删除失败')
                }
            }
        },
        handleSelectionChange (list) {
            let arr = []
            list.map(item => arr.push(item.userId))
            this.checkUserIds = arr
        },
        handleCreate () {
            this.showModel = true
        },
        async getDeptIdList () {
            // this.$axios.get('/test/dept/list').then((res) => {
            //     this.deptList = res
            // })
           const res = await this.$api.getDeptIdList()
           if (res) {
               this.deptList = res
           }
        },
        async getRolesList () {
            // this.$axios.get('/test/roles/allList').then((res) => {
            //     this.roleList = res
            // })
            const res = await this.$api.getRolesList()
            if (res) {
                this.roleList = res
            }
        },
        handleClose () {
            this.showModel = false
            this.handleReset('dialogForm')
        },
        handleSubmit () {
            this.$refs.dialogForm.validate(async valid => {
                if (valid) {
                    // toRow(userForm) 转换为普通数据
                    this.userForm.userEmail += '@163.com'
                    this.userForm.action = this.action
                    // this.$axios.post('/test/users/operate',{
                    //     ...this.userForm
                    // }).then(() => {
                    //     this.showModel = false
                    //     this.$message.success('用户创建成功')
                    //      this.handleReset('dialogForm')
                    //      this.getUerList()
                    // })
                    const res = await this.$api.handleSubmit(this.userForm)
                    if (res) {
                        this.showModel = false
                        this.$message.success('用户创建成功')
                        this.handleReset('dialogForm')
                        this.getUerList()
                    }
                }
            })
        }
    }
}
</script>

5.main.js  挂载全局

app.config.globalProperties.$storage = storage
app.config.globalProperties.$axios = axios
app.config.globalProperties.$api = api


app.use(router)
app.use(ElementPlus,{ size: 'small', zIndex: 3000 })
app.use(store)
app.mount('#app')

6.封装一次后就可以之家复制了,当然你不封装也是没有问题的就promise回调就可以了

7.附上代理

export default defineConfig({
  server: {
    host: 'localhost',
    port: 8080,
    proxy: {
      '/test': {
        target: 'https://www.fastmock.site/mock/5334559accb0157d04d2fa28428accc2/mocks',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/test/, '')
      },
      '/api': {
          target: 'http://localhost:3000',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
      }
      
    }
  },
  plugins: [vue()]
})

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐