说明
结束连续几天的加班,最近的项目终于告一段落,今天抽点时间开始继续写我这篇拖了很久的《用weexplus从0到1写一个app》系列文章。写这篇文章的时候,weexplus的作者已经把weexplus重构了一下,可以同时打包出web端和native端,我这边的ui界面和项目结构也跟着做了一点变化。这里有weexplus官方放出的一个电影APP的demo,有需要的可以去下载看看,然后顺便给weexplus一个star吧!
文章可能会很长,在此分几篇文章来写,先占个坑:
- 用weexplus从0到1写一个app(1)-环境搭建和首页编写
- 用weexplus从0到1写一个app(2)-参数跳转和文章列表及文章详情、搜索页面的编写
- 用weexplus从0到1写一个app(3)-视频列表和视频详情的编写
开始写代码
页面跳转和接收参数
在第一篇的文章《环境搭建和首页编写》中已经写好了首页的代码,现在要从首页的某个文章跳转到文章详情应该怎么做呢?在vue里我们知道是用vue-router来跳转,weexplus中也给我们封装好了类似的导航控制器navigator
。具体使用请看navigtor模块文档
- 页面传参数跳转
主要用后面这段navigator.pushParam('跳转路径String','传递的参数Object')
,如果不需要传参数直接用navigator.push('跳转路径String')
就好了。以下为示例代码:
//commponet/home/news.vue省略n多代码
const navigator = weex.requireModule("navigator");//先引入navigator模块
gotonews(item) {
if (item.category) {
if (item.category.name == "专题") {
//navigator传参数跳转页面
navigator.pushParam(
"root:/busi/news/list.js", {
cid: item.id,
from: "zhuanti"
}
);
}
if (item.category.name != "专题") {
navigator.pushParam("root:/busi/news/detail.js", {
id: item.id
});
}
} else {
navigator.pushParam("root:/busi/news/detail.js", {
id: item
});
}
},
- 接收参数
//busi/news/detail.vue省略n多代码
const navigator = weex.requireModule("navigator");//先引入navigator模块
created(options) {
const globalEvent = weex.requireModule("globalEvent");
globalEvent.addEventListener("onPageInit", () => {
const query = navigator.param();//接收上一个页面传递的参数
this.query = query;
});
},
文章列表和文章详情
先来看文章列表和文章详情的UI界面:
下面拆解一下界面布局:
文章列表界面
可以从分解图中看到文章列表大体上分为三个部分:文章标题,文章封面,文章发布时间。下面废话少说,show my coding!
文章列表数据结构
"article_list": [
{
"id": "7019",//文章id
"title": "Super Star吉他谱_S.H.E_弹唱谱扫弦版",//文章标题
"haslitpic": 1,
"pic": {
"src": "/180203/21562a414_lit.jpg",
"url": "/180203/21562a414_lit.jpg"
},//文章封面
"description": "Super Star吉他谱,扫弦版编配",//文章简介
"pubdate": "2018-02-03 21:55:23",//文章发布时间
"category": {
"name": "图片谱"//文章分类
},
}]
列表布局代码
weex默认是flex布局,css方面就很简单了,对flex不熟悉的推荐看一下阮一峰的flex文章,在这里就不贴代码了。
//component/news-item.vue省略n多代码
<template>
<div class="news-items">
<div v-if="type==1" class="item-box" @click="gotonews(item.id)" v-for="(item,index) in newsItems" :key="index">
<div class="item-left">
<text class="left-text">{{item.title}}</text>
<div class="left-line"></div>
<text class="left-time" v-if="item.category && item.category.name && item.category">{{item.category.name}}</text>
<text class="left-time" v-else>{{item.pubdate}}</text>
</div>
<div class="item-right">
<img :src="item.pic.src" mode="aspectFill" class="litpic">
</div>
</div>
<div class="item-box2" v-if="type==2" @click="go