Vue項目中簡易演示axios解耦
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': '' } } } } }
步驟2:
import axios from 'axios' const service = axios.create({ baseURL: '/api', timeout: 1000 }) export default service
步驟3
import request from '@/utils/request' export function getSug(params) { return request({ url: "/sug", method: 'get', params }) }
步驟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>
查看network

恭喜成功地把axios分離了

浙公網安備 33010602011771號