小程序中有很多好用的API,整个项目我们是用vue实现的,使用小程序的内嵌网页功能完成交互。
使用小程序的 web-view 标签将vue项目在小程序中运行。大概的背景就是这样。接下来介绍具体怎么完成微信小程序与vue内嵌页面实现地图定位功能。
1.首先在index.html中引入微信jssdk
script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"/script2.在小程序中
web-view src="{{url}}"/web-view3.在vue组件中,点击获取地图位置按钮,触发事件。
//携带参数进入小程序,使用小程序地图定位API fixPosition() { //保存当前地址,以便从小程序中返回时使用 let jumpUrl = window.location; //传递多个参数时用&连接 let path = `/pages/address/address?address=${this.warehouse.local}&jumpUrl=${jumpUrl}` //使用navigateTo跳转到小程序路径中 window.wx.miniProgram.navigateTo({ url: path }) }4.在小程序address.js中
4.1在data中定义传递过来的变量,Id和jumpUrl
4.2在onload中,将从vue中传递过来的值赋给Id和jumpUrl
4.3getCenterLocation中调用小程序Api wx.getLocation,wx.chooseLocation获取定位,并且将进行参数返回处理,详细介绍如下
4.4在onReady中调用一下getCenterLocation
Page({ data: { Id:``, jumpUrl:`` }, onLoad: function(options) { this.setData({ Id:options.Id, jumpUrl: options.jumpUrl }) }, onReady: function(e) { // 使用 wx.createMapContext 获取 map 上下文 this.mapCtx = wx.createMapContext('myMap'); this.getCenterLocation() }, getCenterLocation: function() { let that = this; wx.getLocation({ type: 'wgs84', //返回可以用于wx.openLocation的经纬度 success: function(res) { let latitude = res.latitude let longitude = res.longitude wx.chooseLocation({ latitude: latitude, longitude: longitude, scale: 28, success: function(res) { this.address = res.address rePage.setData({ //携带选择的地址res.address返回到vue内嵌界面中 url: that.data.jumpUrl + `?address=${res.address}` }) console.log(this.address) wx.navigateBack({ delta: 1 }) } }) } }) },})5.在vue组件中将小程序传过来的值付给定义为位置的这个参数local,注意,由于小程序与vue的生命周期的问题,赋值需要写在 beforeRouteUpdate中,关于vue路由钩子的介绍详细可参考vue路由钩子官方文档
beforeRouteUpdate(to, from, next) { if(this.$route.query.address){ this.warehouse.local=to.query.address; } next() },结果展示如下:
以下这篇文章给了我很多帮助,可以参考微信小程序与内嵌网页交互实现支付功能













