微信小程序入门(3)

微信小程序之数据传递

特定元素上的数据获取

这种情况最常见于点击某个对象,通过获取该对象的id请求api获取该对象的详细数据。我们来看一下如何获取点击对象的数据。

事先准备:先建两个页面hello和world,通过点击hello页面上的按钮跳转到world页面。

数据获取步骤:

  • 对组件通过data-xxx="xxx"赋值
  • 通过event.currentTarget.dataset.xxxevent.target.dataset.xxx获值

在我的例子中,我现在hello.wxml页面中添加

1
2
<button data-id="a" bindtap="toWorld">A跳转到world页面</button>
<button data-id="b" bindtap="toWorld">B跳转到world页面</button>

在hello.js中添加

1
2
3
4
5
6
7
Page({
data:{},
toWorld: function(event){
var id = event.currentTarget.dataset.id;
console.log(id);
}
})

我分别点击两个按钮。

页面跳转数据传递

继续使用上述例子,在hello.js中添加跳转功能,在跳转时传递数据

1
2
3
4
5
6
7
8
9
Page({
data:{},
toWorld: function(event){
var id = event.currentTarget.dataset.id;
wx.navigateTo({
url: '../world/world?id=' + id
})
}
})

?后面写完参数记得加=,我发现自己老是忘记,然后找了半天为什么数据没有传输成功。

我们看一下官方文档
所以我们在world.js中添加

1
2
3
4
5
6
7
8
9
Page({
data:{},
onLoad:function(options){
var id = options.id;
this.setData({
id: id
});
},
})

然后在world.wxml中修改一下页面

1
2
3
4
<text>World页面</text>
<view>
<text>{{id}}</text>
</view>

重新编译,测试结果。

模板数据的传递

主要是在template中使用

1
data="{{数据}}"
  1. 获取数据

这里我们就自定义数据。在hello.js中添加

1
2
3
4
5
6
7
8
9
onLoad: function(options){
var content = {
title: "模板标题",
desc: "模板描述"
};
this.setData({
content: content
});
}
  1. 模板的生成与引用

先建个模板,随便起名,我的叫content。在content-template.wxml中添加

1
2
3
4
5
6
7
8
<template name="contentTemplate">
<view>
<text>{{title}}</text>
</view>
<view>
<text>{{desc}}</text>
</view>
</template>

在hello.js中引用模板,别忘了import

1
<template is="contentTemplate" data="{{...content}}" />

我们可以看到使用

1
data="{{}}"

这里的三个点是指展开该数据对象,这样我们就可以在模板中直接数据绑定对象里的key。

大小写

在“特定元素上的数据获取”章节中,我们使用了event.currentTarge.dataset.id,如果我们在wxml中使用了驼峰式的命名方法,那应该如何取值呢?很多人第一反应是也是用驼峰式,其实不是,要使用全部小写的方式。
重建一个项目,跟上一个差不多
在hello.js中,错误写法

1
2
3
4
getId: function(event){
var postId = event.currentTarget.dataset.postId;
console.log(postId);
}

这时控制台输出的结果是undefined。
需要改为

1
2
3
4
getId: function(event){
var postId = event.currentTarget.dataset.postid;
console.log(postId);
}

这时才能正确取值。

currentTarget与target

区别:

  • event.currentTarget返回绑定事件的元素
  • event.target返回触发事件的元素

我们已经接触过第一个,它返回绑定事件的元素,比如我在button中注册了一个onMyTap事件,那在js中的onMyTap(event)中的event.currentTarget指的就是绑定了该事件的button对象。
那第二个呢?
举个例子:
修改hello.wxml为

1
2
3
4
5
6
7
8
9
10
<view>
<swiper catchtap="onSwiperTab">
<swiper-item>
<button data-id="a">按钮A</button>
</swiper-item>
<swiper-item>
<button data-id="b">按钮B</button>
</swiper-item>
</swiper>
</view>

在hello.js中

1
2
3
4
onSwiperTab:function(event){
var id = event.target.dataset.id;
console.log(id);
}

我们发现绑定事件的元素是swiper父组件,而触发事件的是其子组件swiper-item,因此target的作用就是如此。