web前端入門到實戰:擼兩個天氣小程序

經過最近兩年多的發展,小程序的地位也逐漸越來越高了,各個平臺前赴後繼做了自家的小程序平臺,隨着市場的需求越來愈多,uni-app 是一個使用 Vue.js 開發所有前端應用的框架,開發者編寫一套代碼,可發佈到iOS、Android、H5、以及各種小程序(微信/支付寶/百度/頭條/QQ/釘釘)等多個平臺。即使不跨端,uni-app同時也是更好的小程序開發框架。

效果圖

web前端入門到實戰:擼兩個天氣小程序

web前端入門到實戰:擼兩個天氣小程序

1、獲取位置信息

在定位功能中,本程序用到騰訊地圖的api 以及 騰訊天氣的api接口,
需要到官網中註冊開發者賬號,通過註冊後得到的appKey來請求我們需要的數據,詳細註冊步驟請自行度娘
由於需要用到定位功能,uniapp的getLocation方法獲取到的是當前位置的座標,然後對應騰訊地圖具體城市

uni.getLocation({
    // #ifdef MP-WEIXIN
    type: 'wgs84',
    // #endif
    async success (res) {
        const {latitude, longitude} = res
        const result = await that.ajax({url: 'https://apis.map.qq.com/ws/geocoder/v1', data: {
            location: `${latitude},${longitude}`,
            key: ''
        }})
        let {province, city, district} = result.result.address_component
        that.getData(province, city, district)
    },
    fail(){
        uni.showModal({
          content: '檢測到您沒打開定位權限,是否去設置打開?',
          confirmText: "確認",
          cancelText: "取消",
          success: function (res) {
            if (res.confirm) {
              // #ifdef MP-WEIXIN
              wx.openSetting({
                success: (res) => {
                    that.getIn()
                }
              })
              // #endif
              // #ifdef MP-ALIPAY
              my.openSetting({
                 success: (res) => {
                    that.getIn()
                 }
              })
              // #endif
            }
          }
        });
    }
})
web前端開發學習Q-q-u-n:784783012 ,分享學習的方法和需要注意的小細節,不停更新最新的教程和學習方法(詳細的前端項目實戰教學視頻)

2、查詢天氣

得到城市名後,再用城市名查詢天氣的接口,得到未來幾天的天氣預報。
天氣接口使用騰訊天氣接口api。
在小程序中使用前,要在小程序設置界面,開發設置中添加request合法域名。

methods: {
    async getData(province, city, district){
        const that = this
        const data = await that.ajax({url: 'https://wis.qq.com/weather/common', data: {
            source: 'xw',
            weather_type: 'observe|alarm|air|forecast_1h|forecast_24h|index|limit|tips|rise',
            province: province,
            city: city,
            county: district
        }})
        that.region = [province, city, district]
        if(data.status != 200){
            uni.showToast({
                title: result.message,
                icon: 'none'
            });
            return false;
        }
        if(!data.data.air.aqi_name){
            uni.showToast({
                title: '暫無該地區的天氣信息',
                icon: 'none'
            });
            return false;
        }
        that.data = data.data
    }
}
web前端開發學習Q-q-u-n:784783012 ,分享學習的方法和需要注意的小細節,不停更新最新的教程和學習方法(詳細的前端項目實戰教學視頻)

3、小程序界面

由於沒有什麼審美,缺乏想象力,參考騰訊天氣的界面來做的。功能十分簡單,查看當前地區的天氣和切換其他地區的天氣,查看最近24小時的天氣情況以及最近6天的天氣情況,展示今天的農曆時間。

4、插件使用

想快速完成小程序的搭建,裏面的折線圖採用的uchart.js,
因爲可以兼容支付寶小程序和微信小程序,農曆查詢也是採用的插件calendar.js
折線圖在支付寶小程序中會有模糊的問題,需要做兼容處理

<template>
<!-- #ifdef MP-ALIPAY -->
<canvas canvas-id="canvas" id="canvas" width="750" height="240" style="width:750rpx;height:240rpx;" class="canvas">
</canvas>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<canvas canvas-id="canvas" id="canvas" class="canvas">
</canvas>
<!-- #endif -->
</template>

<script>
var wxCharts = require('../../utils/chart.js');
lineChart = new wxCharts({
    $this: this,
    canvasId: 'canvas',
    type: 'line',
    categories: ['', '', '', '', '' ,''],
    colors: ['#ffad35', '#4fc3f7'],
    background: '#fff',
    animation: true,
    series: [{
        name: '',
        data: that.max,
        format: function (val, name) {
            return val + '°';
        }
    }, {
        name: '',
        data: that.min,
        format: function (val, name) {
            return val + '°';
        }
    }],
    xAxis: {
        disableGrid: true,
        disabled: true,
        axisLine: false
    },
    yAxis: {
        max: Math.max.apply(Math, that.max) * 1 + 0.1,
        disabled: true,
        disableGrid: true,
    },
    legend:{ 
        show: false 
    },
    // #ifdef MP-ALIPAY
    pixelRatio: that.pixelRatio, // 解決支付寶模糊問題
    // #endif
    width: that.cWidth,
    height: that.cHeight
});
</script>

微信小程序有城市選擇組件,支付寶的沒有可以直接使用的城市組件,uniapp官方介紹:支持安裝 mpvue 組件,但npm方式不支持小程序自定義組件(如 wxml格式的vant-weapp),找到一款支付寶可以使用的城市插件:mpvue-citypicker,
城市選擇組件

<template>
    <view class="txt-location" @tap="showCityPicker">
        <view class="icon"></view>
        <block v-if="region.length">{{region[0]}}{{region[1]}}{{region[2]}}</block>
        <block v-else>選擇城市</block>
        <!-- #ifdef MP-WEIXIN -->
        <picker class="city" mode="region" @change="handleChange" :value="region">
            <view class="picker">
                當前選擇:{{region[0]}},{{region[1]}},{{region[2]}}
            </view>
         </picker>
        <!-- #endif -->
    </view>
    <mpvue-city-picker ref="mpvueCityPicker" :pickerValueDefault="pickerValueDefault" @onConfirm="onConfirm"></mpvue-city-picker>
</template>

<script>
import mpvueCityPicker from 'mpvue-citypicker';
export default {
  data() {
    return {
      region: [],
      pickerValueDefault: [0, 0, 1]
    };
  },
  components: {
    mpvueCityPicker
  },
  methods: {
    showCityPicker() {
        // #ifdef MP-ALIPAY
        this.$refs.mpvueCityPicker.show()
        // #endif
    },
    onConfirm(e) {
        if(e.label){
            this.region = e.label.split('-')
            this.getData(this.region[0], this.region[1], this.region[2])
        }
    },
    handleChange(e) {
        this.region = e.detail.value
        this.getData(this.region[0], this.region[1], this.region[2])
    }
  }
};
</script>
web前端開發學習Q-q-u-n:784783012 ,分享學習的方法和需要注意的小細節,不停更新最新的教程和學習方法(詳細的前端項目實戰教學視頻)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章