vue.js请求数据(axios)

mac2022-06-30  97

使用npm安装axios

npm install axios --save

在main.js中引入axios

import axios from "axios";

注册axios到vue,注册axios到vue不能使用use方法(Vue.use(axios))

Vue.prototype.$http = axios;//$http为自定义的,Vue.prototype 为注册全局方法 其他任何组件都可以使用

之后就可以到页面使用

执行GET请求

<script type="text/ecmascript-6"> export default { methods: function () { this.$http.get('/user', {"id": 123})    .then(res => { console.log(res.data); })    .catch(err => {     console.log(err.msg)    }) } }; </script>

 

执行POST请求

<script type="text/ecmascript-6"> export default { methods: function () { this.$http.post('/user', { firstName: 'Fred', lastName: 'Flintstone' })   .then(res => { console.log(res.data); })   .catch(err => { console.log(err.msg); }) } }; </script>

一次并发多个请求

function getUserAccount(){ return axios.get('/user'); } function getUserPermissions(){ return axios.get('/user/permissions'); } axios.all([getUserAccount(),getUserPermissions()]) .then(axios.spread(function(acct,perms){ //当这两个请求都完成的时候会触发这个函数,两个参数分别代表返回的结果 }))

 

转载于:https://www.cnblogs.com/YAN-HUA/p/9143993.html

相关资源:vue推荐使用的axios库
最新回复(0)