注:笔者是自学小程序,自身开发经验不足,代码肯定存在不规范和不足,该博客参考一下就好
完整项目代码:https://github.com/zim-keavin/wxapp-cloud-demo
实现在小程序中,点击某个组件后跳转到公众号的推文。
注意前提是需将你的小程序和公众号绑定!才能实现跳转。
最终效果:
思想是:先从后台获取数据显示相关推文信息在前端,当点击时跳转到一个新的页面,运用小程序的一个特殊组件web-view跳转到相应的推文。
这里我用的是云开发后台,先配置好数据,将推文链接以及前端要展示的推文相关信息写好
这是第一张图的红框内的wxml代码:
<view class='allContainer' wx:for="{{photoTweets}}" bindtap="toPhotoTweets" data-id='{{index}}'><view class='containerView'><view class='containerText'><view class='title'>{{item.title}}</view><view class='content'>{{item.content}}</view></view><image class='image' src='{{item.photo}}' mode='widthFix'></image></view><view class='solidView'><view class='b'></view></view>
</view>
js代码:
/*** 从云开发数据库中获取推文*/getPhotoTweets: function () {var that = thisdb.collection('photoTweets').get({success(res) {that.setData({photoTweets: res.data.reverse(), // 使最新推文在上面})}})},/*** 公众号推文跳转*/toPhotoTweets: function (e) {var id = e.currentTarget.dataset.id; // 获取点击的推文的数组下标var url = this.data.photoTweets[id].url; // 通过id判断是哪个推文的链接//跳转并传参wx.navigateTo({url: '/pages/showTweets/showTweets?name=photoTweets&url=' + url,})},
.allContainer{margin: 45rpx;
}
.containerView{display: flex;
}
.containerText{flex: 1;
}
.content{color: #888;margin-top: 30rpx;
}
.title{font-size: 35rpx;font-weight:500;
}
.image{width: 200rpx;height: 200rpx;margin-top: 8rpx;
}
.b{margin-top: 20rpx;height: 1rpx;width: 80%;background-color: rgb(245, 241, 241);
}
之后重点来了,前面说过要跳转需在新页面用web-view组件,跳转到新页面:
<!--pages/showPhoto/showPhoto.wxml-->
<web-view src="{{url}}"></web-view>
// pages/showPhoto/showPhoto.js
Page({onLoad: function(options) { this.setData({url:options.url // 通过传参实现跳转公众号推文}) },})
还有一点需注意的是 web-view组件暂不支持个人类型小程序,可留意官方文档
如果有更好的方法欢迎提出或者发个链接到评论区,共勉,谢谢!