在小程序(以微信小程序為例)中,傳參主要有以下幾種常見方式:
1. 通過 data - * 屬性傳參(用於事件綁定)
- 在WXML中設置: 在綁定事件的標籤上使用
data - *的形式設置參數。例如:
<view class="container">
<button bindtap="handleClick" data - id="123" data - name="John">點擊傳參</button>
</view>
- 在Page或Component的事件處理函數中獲取: 在對應的
js文件中的事件處理函數裏,通過event.currentTarget.dataset獲取參數。
- 在Page中:
Page({
handleClick: function (e) {
const id = e.currentTarget.dataset.id;
const name = e.currentTarget.dataset.name;
console.log('獲取到的id:', id);
console.log('獲取到的name:', name);
}
});
- 在Component中:
Component({
properties: {},
methods: {
handleClick: function (e) {
const id = e.currentTarget.dataset.id;
const name = e.currentTarget.dataset.name;
console.log('組件中獲取到的id:', id);
console.log('組件中獲取到的name:', name);
}
}
});
2. 頁面跳轉傳參
- 使用
navigateTo或redirectTo傳參:
- 在
js中調用:
Page({
handleJump: function () {
const data = {
id: 456,
message: 'Hello'
};
wx.navigateTo({
url: '/pages/destination/destination?id=' + data.id + '&message=' + data.message
});
}
});
- 在目標頁面接收參數:在目標頁面(如
pages/destination/destination.js)的onLoad生命週期函數中接收參數。
Page({
data: {
id: null,
message: null
},
onLoad: function (options) {
this.setData({
id: options.id,
message: options.message
});
}
});
- 使用
navigateToMiniProgram跳轉到其他小程序並傳參:
- 在
js中調用:
Page({
handleJumpToMiniProgram: function () {
const data = {
key1: 'value1',
key2: 'value2'
};
wx.navigateToMiniProgram({
appId: 'targetAppId',
path: 'pages/home/home?id=' + data.key1 + '&message=' + data.key2,
extraData: {
...data
},
success(res) {
console.log('跳轉到其他小程序成功', res);
},
fail(err) {
console.log('跳轉到其他小程序失敗', err);
}
});
}
});
- 在目標小程序接收參數:在目標小程序頁面的
onLoad生命週期函數中通過options獲取path中的參數,通過this.getOpenerEventChannel().receive獲取extraData中的數據。
Page({
data: {
key1: null,
key2: null
},
onLoad: function (options) {
this.setData({
key1: options.id,
key2: options.message
});
const eventChannel = this.getOpenerEventChannel();
eventChannel.receive('extraData', (data) => {
console.log('接收到其他小程序傳來的extraData', data);
});
}
});
3. 組件間傳參
- 父組件向子組件傳參:
- 在父組件的WXML中傳遞:
<view class="parent">
<my - component param1="{{value1}}" param2="{{value2}}"></my - component>
</view>
- 在父組件的js中定義數據:
Page({
data: {
value1: '父組件的值1',
value2: '父組件的值2'
}
});
- 在子組件中接收參數:在子組件的
properties定義中接收。
Component({
properties: {
param1: {
type: String,
value: ''
},
param2: {
type: String,
value: ''
}
},
methods: {
// 組件內方法
}
});
- 子組件向父組件傳參:
- 在子組件中觸發自定義事件並傳參:
Component({
properties: {},
methods: {
handleChildClick: function () {
const data = {
childData: '子組件的數據'
};
this.triggerEvent('childEvent', data);
}
}
});
- 在父組件的WXML中綁定自定義事件並接收參數:
<view class="parent">
<my - component bindchildEvent="handleChildEvent"></my - component>
</view>
- 在父組件的js中處理自定義事件:
Page({
handleChildEvent: function (e) {
const childData = e.detail.childData;
console.log('父組件接收到子組件的數據:', childData);
}
});