数据传递
Max Zhang Lv4

数据传递

在小程序中,数据传递是指在不同页面或组件之间传递数据,以实现数据共享。

获取 dom 的数据

如果需要通过事件传递数据,一般可以使用data字段。

1
<view bindtap="handleTap" data-id="123">点击</view>
1
2
3
4
5
Page({
handleTap(e) {
console.log(e.currentTarget.dataset.id); // 123
},
});

在事件中,可以通过e.currentTarget是触发事件的组件,如果想通过dataset传递属性,需要在对应的 dom 上设置data-前缀。

比如,data-id对应e.currentTarget.dataset.id

组件间传递数据

使用properties属性可以让父组件向子组件传递数据。

父组件:

1
<child prop="123"></child>

子组件:

1
<view>{{prop}}</view>
1
2
3
4
5
6
7
8
Component({
properties: {
prop: {
type: String,
value: "789",
},
},
});

在父组件中,通过prop属性传递数据给子组件,子组件通过properties接收数据。所以,子组件中的prop值为123,而不是默认值789

使用triggerEvent方法可以让子组件向父组件传递数据。

子组件:

1
<view bindtap="handleTap">点击</view>
1
2
3
4
5
6
7
Component({
methods: {
handleTap() {
this.triggerEvent("myevent", { data: "这是一个事件" });
},
},
});

父组件:

1
<child bindmyevent="handleEvent"></child>
1
2
3
4
5
Page({
handleEvent(e) {
console.log(e.detail.data); // 这是一个事件
},
});

在子组件中,通过triggerEvent方法触发事件,父组件通过bindmyevent监听事件。e.detail中包含了事件的数据。

1
2
3
4
5
this.triggerEvent(
"myevent",
{ data: "这是一个事件" },
{ bubbles: true, composed: true }
);

triggerEvent 的参数:

  • type:事件名称
  • detail:事件数据
  • options:事件选项
 评论
评论插件加载失败
正在加载评论插件