VueCli 中安装 axios
介绍 Vue 中安装 axios 的方法。
·
axios 官网: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="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>
方式二:使用 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);
})
后端 springboot 代码
@RestController
@CrossOrigin
public class HelloController {
@RequestMapping("hello")
public String hello(@RequestBody Map<String, String> username) {
System.out.println(username);
return "Hello world!";
}
}
结果:
更多推荐
已为社区贡献1条内容
所有评论(0)