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': ''
                }
            }
        }
    }
}
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分离了

posted @ 2019-10-24 22:43  润润润  阅读(561)  评论(0编辑  收藏  举报