渲染数据代码示例:
<template>
<view class="content">
<view class="page-section indexListBox">
<view class="indexList" v-for="(item , index) in homePosts" :key="index">
<view class="title">{{item.title}}</view>
<view v-html="item.content"></view>
</view>
</view>
</view>
</template>
<style>
.indexList uni-image {
width: 100%;
height: 130px;
background: #eaeaea;
}
.indexList {
margin-top: 15px;
margin-bottom: 15px;
}
.indexList .title {
background: #000;
color: #fff;
font-size: 16px;
line-height: 37px;
padding: 0 10px;
margin-top: -5px;
}
.indexListBox{
margin-top: 20px;
}
</style>
<script>
export default {
data() {
return {
homePosts:[],
}
},
onLoad() {
//教程 uni-app:渲染app的首页文章数据第一步:将该方法加入onLoad中,使页面一加载的时候就获取文章列表
this.getHomePosts();
},
methods:{
getHomePosts(){
var _self = this;
uni.request({
url: 'http://192.168.1.156:10086/smart-admin-api/article/page/list',//接口地址
header: {
'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
},
success: (res) => {
// 请求成功之后将文章列表数据赋值给homePosts
_self.homePosts=res.data.data.list;//根据API数据找到对应的集合
}
});
}
}
}
</script>
uni-app中调取接口的三种方式:
1、最普通的调取接口方法,不能解决异步
uni.request({
url:'',
data:'',
method:'', //get、post、delete
header:{},
success:res=>{},
fail:()=>{},
complete:=>{}
})
2、利用ES6的Promise对象解决异步问题的方法
uni.request({
url:'',
data:'',
method:'', //get、post、delete
header:{}
}).then((result)=>{
result将返回一个数组[error,{NativeData}]
})
NativeData:调取接口后返回的原生数据。
uni.request({
url:'/api/getIndexCarousel.jsp',
}).then(result=>{
let [err,res]=result;
if(res.stat0usCode===200){
this.carouselData=res.data;
};
if(res.statusCode===404){
console.log("请求的接口没有找到");
}
})
(1)对数组的解构:
var arr=[10,20,30];
var [a,b,c]=arr; //对数组arr进行结构,并将数据给了abc三个变量
(2)对对象的解构:
var obj={a:10,b:20,c:30};
var w={
...obj
}
3、async/await ES6的终极解决异步问题的办法
async:用在函数定义的前面。 async request(){ //函数体; }
await:用在标明了async关键字的函数内部 异步操作的前面。
methods: {
async request(){
let result=await uni.request({
url:'/api/getIndexCarousel.jsp',
})
let [err,res]=result;
if(res.statusCode===200){
this.carouselData=res.data
}
}
},
onLoad(){
this.request();
}