微信小程序根目录下的 `app.json` 文件用来对微信小程序进行全局配置,决定页面文件的路径、窗口表现、设置网络超时时间、设置多 tab 等
{
"pages": [
"pages/index/index",
"pages/books/books"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "好程序员",
"navigationBarTextStyle": "black"
},
"tabBar": {
"color": "#aaaaaa",
"selectedColor": "#ff0000",
"list": [
{
"pagePath": "pages/index/index",
"text": "福利",
"iconPath": "/assets/tabbar/index.png",
"selectedIconPath": "/assets/tabbar/index-on.png"
},
{
"pagePath": "pages/books/books",
"text": "书城",
"iconPath": "/assets/tabbar/book.png",
"selectedIconPath": "/assets/tabbar/book-on.png"
}
]
}
}
App类与应用级别的生命周期
注册小程序。接受一个 `Object` 参数,其指定小程序的生命周期回调等。`App()` 必须在 `app.js` 中调用,必须调用且只能调用一次。不然会出现无法预期的后果。
App({
// 整个应用程序的入口
onLaunch() {
wx.login({
success: res => console.log('登录', res.code)
})
},
globalData: {
userInfo: null,
}
})
小程序初次启动时请求用户授权地理定位
# app.js
App({
onLaunch() {
// 获取用户的地理定位的授权
wx.getSetting({
success(res) {
console.log('当前用户的授权列表', res.authSetting)
// 如果用户未授权地理定位
if (!res.authSetting['scope.userLocation']) {
// 无须用户触发,直接弹框请求用户同意使用地理定位
// 当用户拒绝过一次后,这段代码没用了
wx.authorize({
scope: 'scope.userLocation',
success (res) {
console.log('地理定位:用户点击了同意', res)
},
fail (err) {
console.log('地理定位:用户点击了拒绝', res)
}
})
}
}
})
}
})
# app.json
{
"pages": [],
"permission": {
"scope.userLocation": {
"desc": "为了给你更好的服务,希望使用你的地理定位"
}
}
}
使用地理定位
<button bindtap='getLngLat'>获取用户经纬度</button>
<map class="map"
longitude='{{latLng.longitude}}'
latitude='{{latLng.latitude}}'
></map>
<button bindtap='navTo'>导航去这里</button>
Page({
data: {
latLng: {}
},
getLngLat() {
var that = this
wx.getSetting({
success(res){
if(res.authSetting['scope.userLocation']) {
// 如果用户已经同意过地理定位,直接获取经纬度
wx.getLocation({
success(res) {
console.log('用户位置', res)
that.setData({latLng: res})
}
})
}else{
// 如果用户已经拒绝过地理定位,我们要打开微信内置的设置页面,让用户自己选择授权
wx.openSetting({
success(res) {
console.log('用户手动选择授权', res)
}
})
}
}
})
},
navTo() {
wx.openLocation({
latitude: this.data.latLng.latitude,
longitude: this.data.latLng.longitude,
name: '深圳',
address: '广东省深圳市'
})
}
})
onShareAppMessage 实现转发
<button open-type='share'>
<view>拼团</view>
</button>
Page({
data: {},
// 实现转发的两种方案(胶囊按钮、button.open-type='share')
onShareAppMessage(e) {
console.log('转发', e)
if(e.from==='menu') {
return {
title: '招聘年薪百万',
path: 'pages/listen/listen',
imageUrl: 'https:70.jpg.webp'
}
}else if(e.from==='button') {
return {
title: '我正在拼团...',
path: 'pages/listen/listen',
imageUrl: 'https://img20.0.jpg.webp'
}
}
}
})
onPageScroll 监听页面滚动
<!-- 使用scrollTop -->
<button bindtap='backToTop'>回到指定位置</button>
App({
// 页面滚动
onPageScroll(e) {
console.log('页面滚动', e.scrollTop)
},
// 使用scrollTop滚动到页面的任何位置
backToTop() {
wx.pageScrollTo({
scrollTop: 133,
duration: 2000
})
}
})