安装axios
cnpm install axios
在src里面创建utils文件夹,创建http.js文件,用来写调用方法(POST,GET)。
import axios from ‘axios‘ // request拦截 axios.interceptors.request.use(config => { return config }, error => { return Promise.reject(error) }) // response拦截 axios.interceptors.response.use(response => { return response }, error => { return Promise.resolve(error.response) }) var baseURL = ‘http://127.0.0.1:8082/springboot/‘// 本机 export default { ‘baseURL‘: baseURL, post (url, data) { return axios({ method: ‘post‘, baseURL: baseURL, // 如果`url`不是绝对地址,那么`baseURL`将会加到`url`的前面 url, data: JSON.stringify(data), timeout: 15000, headers: { // 请求头 ‘X-Requested-With‘: ‘XMLHttpRequest‘, ‘Content-Type‘: ‘application/json; charset=UTF-8‘ } }).then( response => { return response.data } ) }, get (url, params) { return axios({ method: ‘get‘, baseURL: baseURL, url, params, // 选项是要随请求一起发送的请求参数----一般链接在URL后面 timeout: 10000, headers: { ‘X-Requested-With‘: ‘XMLHttpRequest‘ } }).then( (response) => { return response.data } ) } }
在main.js中引入http.js
import http from ‘./utils/http‘
Vue.prototype.$http = http
调用页面:
<template> <div> <p>{{ message }}</p> <button @click="ss">点击</button> </div> </template> <script> export default { name: ‘HelloWorld‘, data () { return { message: ‘测试冒泡事件‘ } }, methods: { async ss () { let data = { ‘name‘: ‘123‘, ‘age‘: 18 } // let res = await http.post(‘listOutpatientExpenses‘, data) let res = await this.$http.get(‘getUser‘, data) this.message = res } }, mounted () { } } </script>