您现在的位置是:网站首页> 编程资料编程资料
Vue实现让页面加载时请求后台接口数据_vue.js_
2023-05-24
316人已围观
简介 Vue实现让页面加载时请求后台接口数据_vue.js_
让页面加载时请求后台接口数据
{{title}}
Vue请求后台数据几种方式
常用的为:vue-resource、axios、fetch-jsonp
1、vue-resource官方提供的vue的一个插件
①安装:在项目根目录进行安装:cnpm install vue-resource --save
save说明:将此插件名插入到pachage.json文件中,别人在使用时,直接npm install,就会安装package.json里的所配置的软件插件名称了。
②引入vue-resource
在main.js中引入这个插件,并使用这个插件
import VueResource from 'vue-resource' Vue.use(VueResource );
③示例:
export default{ data(){ return { msg:'我是一个首页组件msg', flag:true, list:[] } }, methods:{ getData(){ //请求数据 var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1'; this.$http.get(api).then((response)=>{ console.log(response); //注意this指向 this.list=response.body.result; },function(err){ console.log(err); }) } }, mounted(){ /*生命周期函数*/ this.getData(); } }2、axios的使用
安装 cnpm install axios --save
哪里用哪里引入axios
import Axios from 'axios'; export default{ data(){ return { list:[] } }, methods:{ getData(){ var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1'; Axios.get(api).then((response)=>{ this.list=response.data.result; }).catch((error)=>{ console.log(error); }) } }, mounted(){ /*生命周期函数*/ this.getData(); } }3、fetch-jsonp不受跨域限制
安装 cnpm i fetch-jsonp -S
用法:在项目中引入
import fetchJsonp from fetch-jsonp let domain=`http://api.douban.com/v2/movie/top250` fetch(this.domain,{ start:0, count:20, method:'GET', mode:'no-cors' }).then(response=>{ console.log(response) console.log(response.json()) return response.json() }).then(res=>{ console.log(res) }).catch(e=>{ console.log(e) })以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
您可能感兴趣的文章:
相关内容
- vue再次进入页面不会再次调用接口请求问题_vue.js_
- vue使用keep-alive如何实现多页签并支持强制刷新_vue.js_
- Vue3-KeepAlive,多个页面使用keepalive方式_vue.js_
- 关于vue-admin-element中的动态加载路由_vue.js_
- js如何去除数组中的empty undefined空项_javascript技巧_
- vue导入excel文件,vue导入多个sheets的方式_vue.js_
- vue实现滚动条到顶部或者到指定位置_vue.js_
- vue中的vue-router query方式和params方式详解_vue.js_
- Vue源码cached解析_vue.js_
- Vue源码makeMap函数深入分析_vue.js_
