Vue项目中简易演示axios解耦
2024-10-21 09:58:58
Vue项目中简易演示axios解耦
-api\sug.js (配置获取方法)
-utils\request.js (配置自定义axios实例)
-vue.config.js (解决跨域)
-demo.vue (引入并调用请求方法api\sug.js__function getSug())
步骤1:
module.exports = {
outputDir: 'dist', //build输出目录
assetsDir: 'assets', //静态资源目录(js, css, img)
lintOnSave: true, //是否开启eslint
devServer: {
open: false, //是否自动弹出浏览器页面
host: "localhost",
port: '8080',
https: false, //是否使用https协议
hotOnly: false, //是否开启热更新
proxy: {
'/api': {
target: 'https://suggest.taobao.com', //API服务器的地址
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
vue.config.js
步骤2:
import axios from 'axios' const service = axios.create({
baseURL: '/api',
timeout: 1000
}) export default service
utils\request.js
步骤3
import request from '@/utils/request' export function getSug(params) {
return request({
url: "/sug",
method: 'get',
params
})
}
api\sug.js
步骤4
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</div>
</template> <script>
import HelloWorld from './components/HelloWorld.vue'
import request from './utils/request.js'
import { getSug } from './api/sug.js'
export default {
name: 'app',
components: {
HelloWorld
},
mounted(){
getSug({
code:"utf-8",
q:"卫衣"
})
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(err)
})
}
};
</script> <style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
App.vue
查看network
恭喜成功地把axios分离了
最新文章
- OpenCV2计算机编程手册(一)操作像素
- 高性能网站架构设计之缓存篇(5)- Redis 集群(上)
- C语言 指针例解
- linux文本模式下使用PPPOE拨号ADSL上网的方法
- DSP using MATLAB 示例Example3.4
- 【BZOJ】3196: Tyvj 1730 二逼平衡树(区间第k小+树套树)
- appium for windows 环境搭建
- Ajax Array Json 示例
- Go语言之defer
- android 焦点问题
- xmlplus 组件设计系列之十 - 网格(DataGrid)
- Redis学习-SortedSet
- poi合并单元格同时导出excel
- 判断是否AVL平衡二叉书
- 05-Git
- 软件测试实验四----mujava变异测试
- saltstack实战1-salt-syndic
- Android View相关知识问答
- ipconfig命令查ip的时候给别人看有危险吗
- mysql更改数据文件目录及my.ini位置