您的位置:首页 > 移动开发 > 微信开发

微信小程序(页面跳转详解)

2017-02-25 10:12 861 查看
本例中实现页面跳转主要用到了一下几个页面,分别是:

下面是posts.wxml文件:

<import src="post-item/post-item-template.wxml"/>
<block wx:for="{{posts_key}}" wx:key="{{index}}">
<!--使用模板-->
<view catchtap="onPostTap" data-postid="{{item.postId}}">
<template is="postItem" data="{{...item}}" />
</view>
</block>


①该页面就是跳转之前的页面,首先使用了一个block标签,在组件上使用wx:for控制属性绑定一个数组,即可使用数组中各项的数据重复渲染该组件。默认数组的当前项的下标变量名默认为index,数组当前项的变量名默认为item,可能大家会说在这里为什么还要使用wx:key=”{{index}}呢?因为如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态(如 中的输入内容, 的选中状态),需要使用 wx:key 来指定列表中项目的唯一的标识符。如果不使用wx:key=”{{index}}的话,可能会发出警告信息,如图所示:



这里的data-postid=”{{item.postId}}”是自定义属性,为下面的页面跳转传参做准备,在组件中可以定义数据,这些数据将会通过事件传递给service。书写方式为:以data-开头,多个单词由连字符“”-“”连接,不能有大写(大写会自动转换成小写)如data-element-type,最终会在event.currentTarget.dataset中会将字符串转成驼峰。elementType。

②这里的一段代码是为了引入template模板。

下面是template模板文件代码:

<template name="postItem">
<view class="post-container">
<view class="post-author-date">
<image class="post-author" src="{{avatar}}">
</image>
<text class="post-date">{{date}}</text>
</view>
<text class="post-title">{{title}}</text>
<image class="post-image" src="{{imgSrc}}"></image>
<text class="post-content">{{content}}</text>
<view class="post-like">
<image class="post-like-image" src="../../images/icon/chat.png"></image>
<text class="post-like-font">{{collection}}</text>
<image class="post-like-image" src="../../images/icon/view.png"></image>
<text class="post-like-font">{{reading}}</text>
</view>
</view>
</template>


③下面是posts.js文件:

//引入数据文件
var postsData=require("../../data/posts-data.js");
Page({
data:{

},
onLoad:function(options){
//页面初始化,options为页面跳转所带来的参数
this.setData({
posts_key:postsData.postList
});
},
onPostTap:function(event){
var postId = event.currentTarget.dataset.postid;
// console.log("postId is"+postId);
wx.navigateTo({
url: 'post-detail/post-detail?id='+postId
})
}
})


这里的

wx.navigateTo({
url: 'post-detail/post-detail?id='+postId
})


是带参跳转的,一个参数就用’post-detail/post-detail?id=’+postId,如果多个参数就用’post-detail/post-detail?id=’+postId+‘abc=’+’123’,那么如何在新的页面里接收页面传递过去的参数呢?

很简单,在onLoad函数里面来接收,如下:

var postsData=require("../../../data/posts-data.js")
Page({
onLoad:function(option
acbd
){
//onLoad生命周期函数,在一个页面中只会加载一次
//在onLoad声明周期函数中,option为页面跳转所带来的参数
console.log(option);
var postId = option.id;
var postData = postsData.postList[postId];
//console.log(postData);

//this.setData做数据绑定
//目前不能使用this.data
this.setData(
{
postData:postData
}
)
//console.log(postData);
}
})


在onLoad生命周期函数,在一个页面中只会加载一次,在onLoad声明周期函数中,option为页面跳转所带来的参数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: