共计 1343 个字符,预计需要花费 4 分钟才能阅读完成。
将 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); | |
}) |
正文完