引入axios.js

main.js引入
import './plugins/axios'
将 axios 绑定到 vue 原型上
npm install axios
main.js中导入并绑定
import Vue from 'vue'
import App from './App'
import axios from 'axios'
Vue.prototype.$axios = axios
new Vue({
el: '#app',
components: { App },
template: '<App/>'
})
调用
<template>
<div id="app">
<button @click="hello">点击</button>
</div>
</template>
<script>
export default {
name: "App",
methods: {
hello() {
// this.$axios({
// method: "get",
// url: "http://localhost:1313/hello"
// }).then(res => {
// console.log(res.data);
// });
this.$axios.get("http://localhost:1313/hello").then(response => {
console.log(response.data);
});
}
}
};
</script>
<style></style>
使用 vue-axios
npm install --save axios vue-axios
main.js 中安装
import Vue from 'vue'
import App from './App'
import axios from 'axios'
import VueAxios from 'vue-axios'
// VueAxios 与 axios 的位置不能交换,否则出现 TypeError: Cannot read property 'protocol' of undefined
Vue.use( VueAxios , axios)
new Vue({
el: '#app',
components: { App },
template: '<App/>'
})
调用
<template>
<div id="app">
<button @click="handleClick">点击</button>
</div>
</template>
<script>
export default {
name: "App",
methods: {
handleClick() {
// this.axios({
// method: "get",
// url: "http://localhost:8081/hello"
// }).then(res => {
// console.log(res.data);
// });
this.axios.get("http://localhost:8081/hello").then(response => {
console.log(response.data);
});
}
}
};
</script>
<style></style>
post请求
this.axios({
method: "post",
url: "http://localhost:8081/hello",
data: {
username: "admin",
password: "123"
}
}).then((res)=>{
console.log(res.data);
})
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。