微信小程序开发实现点击按钮跳转页面,需要遵循以下步骤:
1. 在小程序的`app.json`文件中配置页面路径。例如,将页面路径设置为`pages/index/index`。
```json
{
"pages": [
"pages/index/index",
"pages/about/about"
]
}
```
2. 在`pages/index/index`页面中,编写一个点击事件处理函数,用于触发页面跳转。
```javascript
Page({
onLoad: function () {
// 初始化数据
this.data = {};
},
// 点击按钮跳转到其他页面
goToOtherPage: function () {
wx.navigateTo({
url: '/pages/other-page/other-page'
});
}
});
```
3. 在`pages/index/index`页面中,添加一个按钮,并为其绑定点击事件处理函数。
```html
```
4. 在`pages/other-page/other-page`页面中,编写一个返回结果的处理函数,用于返回跳转页面的数据。
```javascript
Page({
data: {
result: null
},
onLoad: function (options) {
// 获取跳转页面的数据
const that = this;
wx.request({
url: 'https://example.com/api/getData',
success: function (res) {
that.setData({
result: res.data
});
},
fail: function (err) {
console.log(err);
}
});
},
// 返回跳转页面的数据
goBack: function () {
wx.navigateBack({
delta: 1,
success: function () {
console.log('返回上一页');
},
fail: function (err) {
console.log(err);
}
});
}
});
```
5. 在`pages/index/index`页面中,为按钮添加点击事件处理函数,用于触发跳转页面。
```javascript
Page({
onLoad: function () {
// 初始化数据
this.data = {};
},
// 点击按钮跳转到其他页面
goToOtherPage: function () {
wx.navigateTo({
url: '/pages/other-page/other-page'
});
},
// 点击按钮返回上一页
goBack: function () {
wx.navigateBack({
delta: 1,
success: function () {
console.log('返回上一页');
},
fail: function (err) {
console.log(err);
}
});
}
});
```
6. 在`pages/other-page/other-page`页面中,编写一个返回结果的处理函数,用于返回跳转页面的数据。
```javascript
Page({
data: {
result: null
},
onLoad: function (options) {
// 获取跳转页面的数据
const that = this;
wx.request({
url: 'https://example.com/api/getData',
success: function (res) {
that.setData({
result: res.data
});
},
fail: function (err) {
console.log(err);
}
});
},
// 返回跳转页面的数据
goBack: function () {
wx.navigateBack({
delta: 1,
success: function () {
console.log('返回上一页');
},
fail: function (err) {
console.log(err);
}
});
}
});
```
7. 在`pages/index/index`页面中,为按钮添加点击事件处理函数,用于触发跳转页面。
```javascript
Page({
onLoad: function () {
// 初始化数据
this.data = {};
},
// 点击按钮跳转到其他页面
goToOtherPage: function () {
wx.navigateTo({
url: '/pages/other-page/other-page'
});
},
// 点击按钮返回上一页
goBack: function () {
wx.navigateBack({
delta: 1,
success: function () {
console.log('返回上一页');
},
fail: function (err) {
console.log(err);
}
});
}
});
```