本实例实现新闻列表和新闻详情功能,使用到如下接口:
列表接口:
https://unidemo.dcloud.net.cn/api/news
详情接口:
https://unidemo.dcloud.net.cn/api/news/36kr/ + id (id 为新闻id,上个页面传过来的)
开发中使用到 uListMedia 代码块,代码块设置如下:

自定义代码块:

"uListMedia": {
"body": [
"",
"\t",
"\t\t",
"\t\t\timage>",
"\t\t\t",
"\t\t\t\t{{item.title}}view>",
"\t\t\t\t{{item.content}}view>",
"\t\t\tview>",
"\t\tview>",
"\tview>",
"view>"
],
"prefix": "ulistmedia",
"project": "uni-app",
"scope": "source.vue.html"
}
创建新项目 news,选择默认模板,该项目为要开发的实例项目:

创建新项目 hello-uniapp,选择默认模板,用于将相关的 js、css、ttf 等文件拷贝至实例项目:

将 hello-uniapp 的 common 拷贝至 news :

news 项目的 App.vue 引入 ./common/uni.css:

将 hello-uniapp 的 static/uni.ttf 拷贝至 news :

修改入口页 news/pages/index/index.vue:

<template>
<view class="content">
<view class="uni-list">
<view class="uni-list-cell" hover-class="uni-list-cell-hover" v-for="(item,index) in news" :key="index" @tap="openinfo" :data-newsid="item.post_id">
<view class="uni-media-list">
<image class="uni-media-list-logo" :src="item.author_avatar">image>
<view class="uni-media-list-body">
<view class="uni-media-list-text-top">{{item.title}}view>
<view class="uni-media-list-text-bottom uni-ellipsis">{{item.created_at}}view>
view>
view>
view>
view>
view>
template>
<script>
export default {
data() {
return {
news: []
}
},
onLoad() {
uni.showLoading({
title: '加载中...',
mask: false
});
uni.request({
url: 'https://unidemo.dcloud.net.cn/api/news',
method: 'GET',
data: {},
success: res => {
console.log(res);
this.news = res.data;
uni.hideLoading();
},
fail: () => {},
complete: () => {}
});
},
methods: {
openinfo(e) {
console.log(e);
var newid = e.currentTarget.dataset.newsid;
console.log(newid);
uni.navigateTo({
url: '../info/info?newsid=' + newid
});
}
}
}
script>
<style>
.uni-media-list-body{height: auto;}
.uni-media-list-text-top{line-height: 1.6em;}
style>
创建详情页 info/info.vue:
<template>
<view class="content">
<view class="title">{{title}}view>
<view class="art-content">
<rich-text class="richText" :nodes="strings">rich-text>
view>
view>
template>
<script>
export default {
data() {
return {
title: '',
strings: ''
}
},
onLoad(e) {
console.log(e);
uni.request({
url: 'https://unidemo.dcloud.net.cn/api/news/36kr/' + e.newsid,
method: 'GET',
data: {},
success: res => {
console.log(res);
this.title = res.data.title;
this.strings = res.data.content;
},
fail: () => {},
complete: () => {}
});
},
methods: {
}
}
script>
<style>
.content{padding: 10upx 2%; width: 96%; flex-wrap: wrap;}
.title{line-height: 2em; font-weight: 700; font-size: 38upx;}
.art-content{line-height: 2em;}
style>
运行效果
列表页:

详情页:

在 pages.json 加入 condition 配置,可以直达某个页面进行调试:
"condition": { //模式配置,仅开发期间生效
"current": 0, //当前激活的模式(list 的索引项)
"list": [{
"name": "test", //模式名称
"path": "pages/info/info", //启动页面,必选
"query": "newsid=5310910" //启动参数,在页面的onLoad函数里面得到。
}
]
}
运行:
