微信小程序 天气助手 快速定位当前城市,实时查看天气情况,空气指数,适当增加衣物,方便出行。
小程序主页面 index.wxml
<view class='container'>
<image class="bcg" src="{{backgroundPath}}" mode="aspectFill"></image>
<view class="search">
<view class="wrapper">
<image src="/img/search.png"></image>
<input placeholder="请输入城市名,快速查询天气信息" bindconfirm="commitSearch" value="{{searchText}}"
placeholder-class="placeholderClass"></input>
</view>
</view>
<!-- 跑马灯效果 -->
<view class="example"style="margin-top:80rpx;" wx:if="text">
<view class="marquee_box">
<view class="marquee_text" style="{{orientation}}:{{marqueeDistance}}px;font-size: {{size}}px;">
<image src="{{adUrl}}" class='ad-image' /> : {{text}}
</view>
</view>
</view>
<!-- 内容 -->
<view class="content" style="margin-top:150rpx;">
<button hidden='true'bindtap="sendNew" type="primary">点我</button>
<!-- 头像 -->
<view class='avatarInfo' catchtap='showBcgImgArea'>
<open-data class='avatar' type='userAvatarUrl'></open-data>
<open-data class='name' type='userNickName'></open-data>
<image class='downArrow' src='/img/down.png'></image>
</view>
<!-- 天气信息 -->
<view class="info">
<view class="city">
<view class="name" bindtap="toCitychoose">
<image class="icon" src='/img/location_s_w.png'></image>
<view class="val">{{cityDatas.basic.parent_city}}</view>
<image class="down" src="/img/down.png"></image>
</view>
<view class="time_hint">
<view class="time">{{cityDatas.update.loc}} 更新 </view>
<view class="time">星期{{weiLaiTianqi.weather[0].week}} ({{weiLaiTianqi.weather[0].nongli}})</view>
</view>
</view>
<view class="tempera">
<view>
<text class="tex_temp">{{cityDatas.now.tmp}}</text>
<text style="font-size:50rpx; position: absolute;top:10px;">°C{{cityDatas.now.cond_txt}}</text>
</view>
<view>
<view class="richu">
<text class="tex_hint"> 日出 {{cityDatas.daily_forecast[0].sr}}</text>
<view style="height:15rpx"></view>
<text class="tex_hint"> 日落 {{cityDatas.daily_forecast[0].ss}}</text>
</view>
</view>
</view>
<view class="pm">
<text>{{cityDatas.now.wind_dir}}:{{cityDatas.now.wind_sc}}级 空气质量:{{kongqizhiliang}}</text>
</view>
<view class="pm">
</view>
</view>
<!-- 7天预报 -->
<view class="guide">
<view class="title" style="font-size:28rpx;">未来天气预报</view>
<view class="guides">
<view class="item" wx:for="{{weiLaiTianqi.weather}}" wx:key="index">
<view class="date i">{{item.shortDate}}</view>
<view class="date i">星期{{item.week}}</view>
<view class="temperature i">{{item.info.day[1]}}</view>
<view class="temperature i">{{item.info.night[2]}}~{{item.info.day[2]}}℃</view>
<view class="temperature i">{{item.info.day[3]}}</view>
<view class="temperature i">{{item.info.day[4]}}</view>
<view class="weather i" style="background:'#fff;'">
<text>{{}}</text>
<!-- <image src="{{weatherIconUrl}}{{item.cond_code_d}}.png" mode="widthFix"></image> -->
</view>
<!-- <view class="wind i">{{item.info.day[3]}}{{item.info.day[4]}}</view> -->
</view>
</view>
</view>
<view class="guide">
<view class="title" style="font-size:28rpx;">今日气象信息</view>
<view class='details'>
<view class='detail' wx:for='{{detailsDic.key}}' wx:key='{{index}}'>
<view>{{detailsDic.val[item]}}</view>
<view>{{cityDatas.now[item]}}</view>
</view>
</view>
</view>
<!-- 生活指数 -->
<!-- <view class="living">
<text class="title">生活指数</text>
<view class="livings">
<view class="livingItem" wx:for="{{cityDatas.lifestyle}}">
<image class="item" src="/img/lifestyle_{{item.type}}.png"></image>
<view style="font-size:30rpx; margin-top:10rpx;">{{item.brf}}</view>
<view style="font-size:20rpx; margin-top:10rpx;">{{lifestyles[item.type]}} </view>
</view>
</view> -->
<view class="living">
<text class="title" style="font-size:28rpx;">今日生活指数</text>
<view class="livingIndex">
<view class="item" wx:for="{{cityDatas.lifestyle}}">
<image class="icon" src="/img/lifestyle_{{item.type}}.png"></image>
<view class='right'>
<view class='key'>{{lifestyles[item.type]}} : {{item.brf}}</view>
<view class='value'>{{item.txt}}</view>
</view>
</view>
</view>
</view>
</view>
</view>
index.wxss
.container {
height: 100%;
display: flex;
flex-direction: column;
color: #fff;
font-size: 30rpx;
}
.bcg {
position: fixed;
z-index: 2;
height: 100%;
width: 100%;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
.search {
position: fixed;
z-index: 4;
left: 0;
top: 0;
right: 0;
width: 100%;
height: 90rpx;
/* background: #40a7e7; */
}
.search .wrapper {
display: flex;
flex-direction: row;
align-items: center;
font-size: 28rpx;
height: 60rpx;
min-height: 60rpx;
margin: 15rpx 50rpx;
/* padding: 0 15rpx; */
box-sizing: border-box;
border: none;
border-bottom: 1rpx solid #fff;
}
.search image {
width: 28rpx;
height: 28rpx;
margin-right: 16rpx;
}
.search input {
flex: 1;
}
.placeholderClass {
color: #fff;
}
.content {
/* position: relative; */
z-index: 2;
}
.avatarInfo {
display: flex;
align-items: center;
padding: 0 50rpx;
}
.avatarInfo .avatar {
height: 90rpx;
width: 90rpx;
border-radius: 50%;
overflow: hidden;
}
.avatarInfo .name {
padding: 0 20rpx;
font-size: 30rpx;
}
.avatarInfo .downArrow {
width: 20rpx;
height: 20rpx;
}
.city {
display: flex;
align-items: center;
justify-content: space-between;
position: relative;
padding: 0 50rpx;
font-size: 66rpx;
}
.city .name {
display: flex;
justify-content: center;
align-items: center;
}
.city .name .val {
max-width: 5em;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 1;
overflow: hidden;
}
.city .name .icon, .city .name .down {
width: 30rpx;
height: 30rpx;
}
.city .name .icon{
margin-right: 20rpx;
}
.city .name .down{
margin-left: 20rpx;
}
/* .city .time{
display: block;
text-align: right;
font-size: 25rpx;
} */
.city .time_hint{
display: flex;
flex-direction: column;
font-size: 25rpx;
}
.tempera {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
position: relative;
padding: 0 0 0 50rpx;
}
.tempera .tex_temp{
font-size: 180rpx;
font-weight: lighter;
}
.info {
padding: 10rpx 0 50rpx;
}
.info .weather{
position: relative;
width: 100%;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.info .weather{
margin-bottom: 30rpx;
}
.info .pm{
margin: 0 0 0 20rpx;
}
.info .pm text{
font-size: 30rpx;
height: 1em;
line-height: 1em;
padding: 10rpx 20rpx;
background: rgba(240, 240, 240, .4);
}
.guide .guides{
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: flex-start;
font-size: 24rpx;
padding-top: 20rpx;
background: rgba(0, 0, 0, .5);
margin-bottom: 20rpx;
overflow-x: scroll;
}
.guide .title{
border-bottom: 1rpx solid rgba(250, 250, 250, .2);
background: rgba(0, 0, 0, .5);
font-size: 24rpx;
height: 80rpx;
line-height: 80rpx;
text-align: center;
}
.guide .item{
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
width: 170rpx;
flex-shrink: 0;
}
.guide image{
width: 44rpx;
}
.guide .i{
padding-bottom: 20rpx;
}
.guide .i {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.guide .i image{
width: 40rpx;
margin-left: 4rpx;
}
.richu {
display: flex;
flex-direction: column;
text-align: left;
}
.richu .tex_hint{
font-size: 30rpx;
height: 1em;
line-height: 1em;
padding: 10rpx 10rpx 10rpx 10rpx;
background: rgba(240, 240, 240, .4);
}
.living .livings{
display: flex;
align-items: center;
flex-wrap: wrap;
background:rgba(0, 0, 0, .6);
margin-bottom:20rpx;
font-size: 24rpx;
}
.living .title{
display: flex;
justify-content: center;
border-bottom: 1rpx solid rgba(250, 250, 250, .2);
background: rgba(0, 0, 0, .6);
font-size: 25rpx;
height: 80rpx;
align-items: center;
line-height: 80rpx;
}
.living .livingItem {
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
padding: 20rpx;
height: 180rpx;
width: 25%;
border-right: 1rpx solid rgba(250, 250, 250, 0.2);
border-bottom: 1rpx solid rgba(250, 250, 250, 0.2);
box-sizing: border-box;
}
.living .livings .livingItem image{
width: 80rpx;
height: 80rpx;
padding: 0 24rpx;
}
.details .detail
{
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
padding: 10rpx 0;
height: 100rpx;
width: 25%;
border-right: 1rpx solid rgba(250, 250, 250, 0.2);
border-bottom: 1rpx solid rgba(250, 250, 250, 0.2);
box-sizing: border-box;
}
.details .detail:nth-child(4n)
{
border-right: none;
}
.details .detail:nth-child(n+9) {
border-bottom: none;
}
.details {
display: flex;
align-items: center;
flex-wrap: wrap;
background:rgba(0, 0, 0, .6);
margin-bottom:20rpx;
font-size: 24rpx;
}
.livingIndex {
background: rgba(0, 0, 0, .6);
margin-bottom: 20rpx;
}
.livingIndex .item {
display: flex;
flex-direction: row;
align-items: center;
border-bottom: 1rpx solid rgba(250, 250, 250, .2);
padding: 20rpx 0;
margin: 0 30rpx;
}
.livingIndex .icon{
width: 80rpx;
height: 80rpx;
padding: 0 24rpx;
}
.livingIndex .item .right{
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: flex-start;
flex: 1;
}
.livingIndex .item .value {
margin-top: 10rpx;
font-size: 26rpx;
}
/* 跑马灯 */
.example {
position: fixed;
z-index: 4;
display: block;
width: 100%;
height: 70rpx;
line-height: 70rpx;
}
.marquee_box {
width: 100%;
position: relative;
}
.marquee_text {
white-space: nowrap;
position: absolute;
top: 0;
display: flex;
flex-direction: row;
}
.ad-image {
width: 40rpx;
height: 40rpx;
margin-right: 10rpx;
margin-top: 15rpx;
}
目录
// miniprogram/pages/main/main.js
const HttpUtil = require('../../http/httpUtil')
const CONFIG = require('../../http/config.js')
let utils = require('../../utils/utils')
const app = getApp();
const key = app.globalData.weatherKey
Page({
/**
* 页面的初始数据
*/
data: {
located: true,
cityDatas: {},
// 用来清空 input
searchText: '',
// 需要查询的城市
searchCity: '',
hourlyDatas: [],
backgroundPath: '/img/main.jpg',
weatherIconUrl: 'https://cdn.heweather.com/cond_icon/',
lifestyles: {
'comf': '舒适度',
'cw': '洗车',
'drsg': '穿衣',
'flu': '感冒',
'sport': '运动',
'trav': '旅游',
'uv': '紫外线',
'air': '空气污染',
'ac': '空调开启',
'ag': '过敏',
'gl': '太阳镜',
'mu': '化妆',
'airc': '晾晒',
'ptfc': '交通',
'fsh': '钓鱼',
'spi': '防晒',
},
detailsDic: {
key: ['tmp', 'fl', 'hum', 'pcpn', 'wind_dir', 'wind_deg', 'wind_sc', 'wind_spd', 'vis', 'pres', 'cloud', ''],
val: {
tmp: '温度(℃)',
fl: '体感温度(℃)',
hum: '相对湿度(%)',
pcpn: '降水量(mm)',
wind_dir: '风向',
wind_deg: '风向角度(deg)',
wind_sc: '风力(级)',
wind_spd: '风速(mk/h)',
vis: '能见度(km)',
pres: '气压(mb)',
cloud: '云量',
},
},
weiLaiTianqi: {},
kongqizhiliang: '',
text: '',
marqueePace: 1, //滚动速度
marqueeDistance: 0, //初始滚动距离
size: 14,
orientation: 'left', //滚动方向
interval: 20, // 时间间隔
adUrl: '../../img/lifestyle_drsg.png',
startTime: '',
wind: "",
windLevel: '',
citycode: '',
uploadCityCode:'',
isFirst: true
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
console.log('onload')
this.reloadWeather();
this.refreshView = this.selectComponent("#refreshView")
this.checkUpdate();
this.uploadLoginInfo();
},
uploadLoginInfo(){
HttpUtil.getDingWeiCityCode( {
data: {
}
}).then(res => {
this.setData({
uploadCityCode:res.data.realtime.city_code
})
this.callyunhanshu()
}, error => {
})
},
weatherHint(){
console.log('未来天气',this.data.weiLaiTianqi)
var weiLaiTianqi=this.data.weiLaiTianqi;
wx.showModal({
title:'今日天气',
content:weiLaiTianqi.weather[0].info.day[1]+'\r\n'+'温度 : '+weiLaiTianqi.weather[0].info.night[2]+'~'
+weiLaiTianqi.weather[0].info.day[2]+'℃'+ '\r\n'+' 风向:'+weiLaiTianqi.weather[0].info.day[3]+'('+weiLaiTianqi.weather[0].info.day[4]+')',
showCancel:false, //默认为true,false去掉取消按钮
confirmText:'确认',//默认是“确认”
success:function(res){
if(res.confirm){
wx.requestSubscribeMessage({
tmplIds: ['JtQizszamUDur7RKRTYA8ssUuMPdjcV8ikcotizaj-o'],
success:(res=>{
console.log('订阅,',res)
// wx.cloud.callFunction({
// name: 'myMessages',
// success(res) {
// console.log('发送成功', res);
// },
// fail(res) {
// console.log('发送失败', res);
// }
// })
})
})
}
}
})
}
,
// checkUpdate(){
// let updateManager = wx.getUpdateManager()
// updateManager.onCheckForUpdate((res) => {
// console.error(res)
// })
// updateManager.onUpdateReady(function () {
// wx.showModal({
// title: '更新提示',
// content: '新版本已下载完成,是否重启应用?',
// success: function (res) {
// if (res.confirm) {
// updateManager.applyUpdate()
// }
// }
// })
// })
// },
startHint() {
var that = this;
var length = that.data.text.length * that.data.size; //文字长度
var windowWidth = wx.getSystemInfoSync().windowWidth; // 屏幕宽度
that.setData({
length: length,
windowWidth: windowWidth,
});
that.runMarquee(); // 水平一行字滚动完了再按照原来的方向滚动
},
runMarquee: function () {
var that = this;
that.data.startTime = setInterval(function () {
//文字一直移动到末端
if (-that.data.marqueeDistance < that.data.length) {
that.setData({
marqueeDistance: that.data.marqueeDistance - that.data.marqueePace,
});
} else {
clearInterval(that.data.startTime);
that.setData({
marqueeDistance: that.data.windowWidth
});
that.runMarquee();
}
}, that.data.interval);
},
reloadWeather() {
if (this.data.located) {
this.init({})
}
},
init(params, callback) {
this.setData({
located: true,
});
wx.getLocation({
success: (res) => {
console.log('位置成功' + res.latitude + '-----' + res.longitude)
this.getWeather(`${res.latitude},${res.longitude}`);
// this.getWeather(`${125.28845},${43.83327}`),
callback && callback()
},
fail: (res) => {
// this.getWeather(`${43.83327},${125.28845}`, '4d03627381fc4035a001e4d89a82cbc7');
wx.stopPullDownRefresh()
}
})
},
getWeather(location) {
HttpUtil.showLoading()
HttpUtil.getWeather({
data: {
location,
key
}
}).then(res => {
HttpUtil.hideLoading()
wx.stopPullDownRefresh()
if (res.statusCode === 200) {
let data = res.data.HeWeather6[0]
if (data.status === 'ok') {
this.clearInput();
this.getDataSuccess(location, data);
} else {
wx.showToast({
title: '获取数据失败',
})
}
}
}, error => {
HttpUtil.hideLoading()
wx.showToast({
title: '获取数据失败',
})
wx.stopPullDownRefresh()
})
},
getweilaiTianqi(cityCode) {
HttpUtil.getweiLaitTianqi(cityCode, {
data: {
}
}).then(res => {
HttpUtil.hideLoading()
wx.stopPullDownRefresh()
// var result =res.data.weather;
// for (var i = 0; i < result.length; i++){
// result[i].shortDate = shortDate(data.weather[i].date);
// }
// var time = res.data.weather[0].date;
// var sheng = res.data.area[0][0] + ":" + res.data.area[1][0];
// var tianqi = res.data.weather[0].info.day[1]
// var wendu = res.data.weather[0].info.night[2] + '~' + res.data.weather[0].info.day[2] + "℃";
// var tishi = res.data.life.info.chuanyi[1]
// console.log(time)
// console.log(sheng)
// console.log(tianqi)
// console.log(wendu)
// console.log(tishi)
var test = res.data;
var windxiang = test.realtime.wind.direct;
var windLevel = test.realtime.wind.power;
for (var i = 0; i < test.weather.length; i++) {
test.weather[i].shortDate = this.shortDate(test.weather[i].date);
}
this.setData({
weiLaiTianqi: test,
wind: windxiang,
windLevel: windLevel
})
if(this.data.isFirst){
this.setData({
isFirst:false
})
// this.weatherHint()
}
}, error => {
HttpUtil.hideLoading()
wx.showToast({
title: '获取数据失败',
})
wx.stopPullDownRefresh()
})
},
shortDate(str) {
var date = new Date(Date.parse(str));
var now = new Date();
var result = (date.getMonth() + 1) + "/" + date.getDate();
if (now.getDate() == date.getDate()) {
result = "今天";
} else if (date.getDate() == now.getDate() + 1) {
result = "明天";
} else if (date.getDate() == now.getDate() + 2) {
result = "后天";
}
return result;
},
getDataSuccess(location, data) {
data.update.loc = utils.formatDate(new Date(), "MM-dd hh:mm");
wx.setStorage({
key: 'cityDatas',
data,
})
this.setData({
cityDatas: data
})
console.log(this.data.cityDatas)
var cityCode = this.data.cityDatas.basic.cid.substring(2, this.data.cityDatas.basic.cid.length);
var zhiliang = this.data.cityDatas.lifestyle[7].brf;
var chuanyihint = this.data.cityDatas.lifestyle[1].txt;
this.setData({
kongqizhiliang: zhiliang,
text: chuanyihint,
cityCode: cityCode
})
this.clearHintAni()
this.startHint();
this.getweilaiTianqi(cityCode)
console.log(this.data.kongqizhiliang)
},
clearHintAni() {
clearInterval(this.data.startTime)
this.setData({
marqueePace: 1, //滚动速度
marqueeDistance: 0, //初始滚动距离
size: 14,
orientation: 'left', //滚动方向
interval: 20, // 时间间隔
})
},
clearInput() {
this.setData({
searchText: '',
})
},
search(val, callback) {
console.log('search')
if (val === '520' || val === '521') {
this.clearInput()
// this.dance()
return
}
wx.pageScrollTo({
scrollTop: 0,
duration: 300,
})
if (val) {
this.setData({
located: false,
})
this.getWeather(val)
}
callback && callback()
},
commitSearch(res) {
let val = ((res.detail || {}).value || '').replace(/\s+/g, '')
console.log("commitSearch" + val)
this.search(val)
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
this.clearHintAni()
this.reloadWeather();
},
onShow: function () {
// this.startHint();
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
onShareTimeline: function () {
return{
title:'一款实时查看天气的小程序'
}
},
toCitychoose() {
wx.navigateTo({
url: '/pages/citychoose/citychoose',
})
},
checkUpdate() {
if (wx.canIUse('getUpdateManager')) {
const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function (res) {
console.log('onCheckForUpdate====', res)
// 请求完新版本信息的回调
if (res.hasUpdate) {
console.log('res.hasUpdate====')
updateManager.onUpdateReady(function () {
wx.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success: function (res) {
console.log('success====', res)
// res: {errMsg: "showModal: ok", cancel: false, confirm: true}
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate()
}
}
})
})
updateManager.onUpdateFailed(function () {
// 新的版本下载失败
wx.showModal({
title: '已经有新版本了哟~',
content: '新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~'
})
})
}
})
}
},
showBcgImgAreas() {
var that = this;
wx.chooseImage({
count: 1,
sizeType: ['original'],
success: function (res) {
console.log(res.tempFilePaths)
that.setData({
backgroundPath: res.tempFilePaths
})
},
})
},
async sendNew(res) {
// wx.cloud.callFunction({
// name: 'login',
// }).then(res => {
// console.log(res)
// console.log(res.result.openid)
// var openid = 'oR0cf0bgQu93Tj65nzfx3qiSDuDs'
// })
this.subscribeMessage()
const db =wx.cloud.database();
// const countResult = await db.collection('userInfo').where({}).count()
// const total =countResult.total
// var result;
// if(total>0){
// db.collection('userInfo').get({
// success(res){
// result=res
// console.log('查询',res)
// var isHave =true;
// for (var i = 0; i < result.data.length; i++){
// console.log('查询',result.data[i])
// }
// if(!isHave){
// db.collection('msg').add({
// data: {
// appid:'wx3b65583cc1040f6b',
// openid:'oR0cf0bgQu93Tj65nzfx3qiSDuDs',
// citycode:this.data.uploadCityCode
// }
// })
// }
// }
// })
// }else{
// db.collection('userInfo').add({
// data: {
// appid:'wx3b65583cc1040f6b',
// openid:'oR0cf0bgQu93Tj65nzfx3qiSDuDs',
// citycode:this.data.uploadCityCode
// }
// })
// }
var that = this
var time = new Date();
// wx.requestSubscribeMessage({
// tmplIds: ['JtQizszamUDur7RKRTYA8ssUuMPdjcV8ikcotizaj-o'],
// success(res) {
// wx.showToast({
// title: '订阅成功',
// })
// wx.cloud.callFunction({
// name: 'myMessages',
// success(res) {
// console.log('发送成功', res);
// },
// fail(res) {
// console.log('发送失败', res);
// }
// })
// wx.request({
// url: 'https://open.onebox.so.com/Dataapi?&query=%E5%A4%A9%E6%B0%94&type=weather&ip=&src=soindex&d=pc&url=weather',
// data: {},
// method: 'GET',
// header: {
// 'Content-Type': "application/json"
// },
// success(res) {
// var time = res.data.weather[0].date;
// var sheng = res.data.area[0][0] + ":" + res.data.area[1][0];
// var tianqi = res.data.weather[0].info.day[1]
// var wendu = res.data.weather[0].info.night[2] + '~' + res.data.weather[0].info.day[2] + "℃";
// var tishi = res.data.life.info.chuanyi[1]
// console.log(time)
// console.log(sheng)
// console.log(tianqi)
// console.log(wendu)
// console.log(tishi)
// },
// })
// wx.cloud.callFunction({
// name: 'openapi',
// data: {
// action: 'sendSubscribeMessage',
// // openid:'oR0cf0bgQu93Tj65nzfx3qiSDuDs',
// // date1:'二手物品',
// // phrase2:'城市',
// // phrase3:'地址',
// // character_string4:'测试',
// // thing5:'人民'
// },
// success(res) {
// console.log('成功', res);
// },
// fail(res) {
// console.log('失败', res);
// }
// })
// }
// })
},
async callyunhanshu(){
wx.cloud.callFunction({
name: 'login',
data:{
citycode:this.data.uploadCityCode
}
}).then(res => {
console.log('login函数',res)
console.log(res.result.openid)
})
},
subscribeMessage(){
//需要订阅的消息模板,在微信公众平台手动配置获取模板ID
let message = 'JtQizszamUDur7RKRTYA8ssUuMPdjcV8ikcotizaj-o';
//如果总是拒绝(subscriptionsSetting,2.10.1库才支持)
if(this.versionCompare('2.10.1')){
wx.getSetting({
success: (res)=> {
console.log('订阅,',res)
if (res.subscriptionsSetting && res.subscriptionsSetting.itemSettings &&
res.subscriptionsSetting.itemSettings[message] == "reject"){
//打开设置去设置
this.openConfirm('检测到您没打开推送权限,是否去设置打开?')
}else {
wx.requestSubscribeMessage({
tmplIds: [message],
success: (res)=> {
console.log('订阅,',res)
if (res[message] == 'accept'){
//用户允许
wx.showToast({
title: '订阅成功',
})
}
},
fail: (res)=> { console.info(res) },
})
}
}
})
}else if(this.versionCompare('2.4.4')){
wx.requestSubscribeMessage({
tmplIds: [message],
success: (res)=> {
if (res[message] == 'accept'){
//用户允许
wx.showToast({
title: '订阅成功',
})
}
},
fail: (res)=> { console.info(res) },
})
}
},
//打开设置
openConfirm(message) {
wx.showModal({
content: message,
confirmText: "确认",
cancelText: "取消",
success: (res) => {
//点击“确认”时打开设置页面
if (res.confirm) {
wx.openSetting({
success: (res) => {
console.log(res.authSetting)
},
fail: (error) => {
console.log(error)
}
})
} else {
console.log('用户点击取消')
}
}
});
},
//基础库版本比较
versionCompare(v) {
const version = wx.getSystemInfoSync().SDKVersion
if (this.compareVersion(version, v) >= 0) {
return true
} else {
return false
}
},
compareVersion: function (v1, v2) {
v1 = v1.split('.')
v2 = v2.split('.')
var len = Math.max(v1.length, v2.length)
while (v1.length < len) {
v1.push('0')
}
while (v2.length < len) {
v2.push('0')
}
for (var i = 0; i < len; i++) {
var num1 = parseInt(v1[i])
var num2 = parseInt(v2[i])
if (num1 > num2) {
return 1
} else if (num1 < num2) {
return -1
}
}
return 0
},
})