yarn add axios
yarn add vue-resource --save-dev
import Vue from 'vue'
/*引入资源请求插件*/
import VueResource from 'vue-resource'
/*使用VueResource插件*/
Vue.use(VueResource)
GET 方法
我们可以简单的读取 JSON 数据,使用 response.data 读取 JSON 数据
<div id="app">
<div v-for="site in info"> {{ site.name }}</div>
</div>
<script type = "text/javascript">
new Vue({
el: '#app',
data () { return {info: null },
mounted () {
axios.get('https://www.runoob.com/try/ajax/json_demo.json')
.then(response => (this.info = response.data.sites))
.catch(function (error) { console.log(error);}) }
})
</script>
GET 方法传递参数格式如下
// 直接在 URL 上添加参数 ID=12345
axios.get('/user?ID=12345')
.then(function (response) {console.log(response); })
.catch(function (error) {console.log(error); });
// 也可以通过 params 设置参数:
axios.get('/user', { params: { ID: 12345}})
.then(function (response) {console.log(response); })
.catch(function (error) {console.log(error);});
POST
axios.post('https://www.runoob.com/try/ajax/demo_axios_post.php')
.then(response => (this.info = response))
.catch(function (error) { console.log(error);});
POST 方法传递参数格式如下:
axios.post('/user', {
firstName: 'Fred', // 参数 firstName
lastName: 'Flintstone' // 参数 lastName
})
.then(function (response) { console.log(response); })
.catch(function (error) {console.log(error); });
执行多个并发请求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
跨域 vue-resource*不再更新
https://www.cnblogs.com/goloving/p/8665799.html
Vue 要实现异步加载需要使用到 vue-resource 库。vue2.0之后,就不再对vue-resource更新,而是推荐使用axios。
<template>
<div class="hello">
<input type="text" v-model="keyword" @keyup="sendJsonP(keyword)" />
<ul>
<li :key="r" v-for="r in result">{{r}}</li>
</div>
</template>
<script>
export default {
name: "Hello",
data() {
return {
keyword: "",
result: ""
};
},
methods: {
sendJsonP(keyword) {
let url =
"https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web";
this.$http
.jsonp(url, {
params: {
wd: keyword
},
jsonp: "cb" //jsonp默认是callback,百度缩写成了cb,所以需要指定下 }
})
.then(res => {
if (res.data.g) {
this.result = res.data.g.map(x => x["q"]);
} else {
this.result = [];
}
});
}
}
};
</script>
vue-cli跨域
// 新建文件 vue.config.js
module.exports = {
// baseUrl:'/',
outputDir: "dist2",
assetsDir: "assets",
lintOnSave: false,
devServer: {
open: true,
host: "localhost",
port: 8081,
https: false,
hotOnly: false,
proxy: {//开发环境(dev)中解决了跨域问题
"/api": {
target: "https://www.runoob.com/try/ajax/", //设置你调用的接口域名和端口号 别忘了加http
// ws: true,
secure: false, // 如果是https接口,需要配置这个参数
changeOrigin: true,
pathRewrite: {
"^/api": ""//用"/api"代替target里面的地址
}
}
}
}
};
axios
.get("/api/json_demo.json")//https://www.runoob.com/try/ajax//json_demo.json
.then(response => (this.info = response.data.sites))
.catch(function(error) {
// 请求失败处理
console.log(error);
});
网友评论