微信小程序开发中的代码片段总结
经过一段时间的微信小程序开发,总结了一些代码片段,主要是以下几个方面:
小程序授权逻辑
const checkPermission = scope =>
new Promise((resolve,reject) => {
wx.getSetting({
success: res => {
// 是否存在认证配置
let hasAuthorized = res.authSetting.hasOwnProperty(scope)
if (hasAuthorized) {
// 已授权
if (res.authSetting[scope]) {
resolve('已授权')
return
}
// 未授权,提示进入小程序设置页面,wx限制:需要主动点击才能执行openSetting(),因此使用modal
wx.showModal({
title: '没有权限',content: '体验该功能需要您授权功能权限,现在前往设置开启',success: res => {
if (res.confirm) {
reject('设置页面')
wx.openSetting()
} else if (res.cancel) {
reject('不进入设置')
}
}
})
}
},fail: err => { reject(err.errMsg) }
})
})
网络微信小程序不同环境下网络请求的不同之处: 校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书
网络请求与拦截器可以使用?fly.js?作为小程序的网络请求库,在使用拦截器等功能时也较为方便。 小程序中一个特殊的地方是:? 判断是否在线
使用globalData全局变量在小程序中将自带的[? 在src中的?
import App './App'
...
const app = new Vue(App)
app.$mount()
Vue.prototype.$globalData = getApp().globalData // 添加该行
然后就可以在其他页面使用该命令操作全局变量了 }
// page B
console.log(this.$globalData.userInfo)
// page C
this.$globalData.userInfo.name: 'yrq110'
注意,在子页面中使用globalData时,将变量赋值的操作放在data中是无效的,如下: export default {
data() {
// 无效
// isIPX: this.$globalData.isIPX
},computed: {
isIPX() {
// 有效
this.$globalData.isIPX
}
},}
SVG图标组件的默认尺寸与预设尺寸在图标组件中加载svg时使用父标签上的尺寸作为默认尺寸,并在传入特定props参数时使用预设尺寸。 业务中碰到了这个问题,使用如下的方法进行了解决:在image组件的load事件处理器中将加载的原始尺寸绑定到style上。 实现了: 1. 默认使用svg标签自带尺寸 2. 当传入size属性则使用预设尺寸 <template>
<image
...
@load="loadHandle"
:style="{ width: !size ? iconWidth + 'rpx' : '100%',height: !size ? iconHeight + 'rpx' : '100%'}"
...
/>
</template>
<script>
export default {
...
data() {
return {
iconWidth: false // 是否加载完毕
}
},props: {
...
size: String
},computed: {
...
getSizeClass() {
let { size } = this
return size || ''
},setSizeStyle() {
this.loaded || this.size) return {}
return {
width: this.iconWidth + 'rpx',height: this.iconHeight + 'rpx'
}
}
},methods: {
loadHandle(e) {
this.loaded = true
// 使用加载后的默认尺寸
const { detail } = e.mp
this.iconWidth = detail.width * 2
this.iconHeight = detail.height * 2
}
}
...
}
</script>
解决无法在组件上绑定class的trick将keyword作为prop属性传入组件并通过Computed属性绑定到class上,这样在外部引用时就可以根据keyword设置自定义的样式了。 组件中的关键代码如下:
return type
}
}
...
}
</script>
在外部引用时就可以使用自定义class来在外部使用样式了:
|