VUE的picker時間日期選擇


  一開始用別人封裝好的W-picker進行時間日期選擇,后來測試的時候發現IOS系統不兼容,后改成原生picker去選擇

  完整代碼

<template>
    <view class="container">
        <view class="uni-padding-wrap uni-common-mt">
            <form @submit="formSubmit">
                <!-- 車輛信息 -->
                <view v-for="(item, indexItem) in truckIdArray" :key='indexItem'>
                    <view class="uni-list">
                        <view class="uni-list-cell">
                            <view class="uni-list-cell-left">
                                車輛信息
                            </view>
                            <view class="uni-list-cell-db">
                                <view class="uni-input">
                                    <view v-if="truckIdArray.length > 1">
                                        <button style="float: right;" type="default" size="mini" @click="removeTruck(indexItem)">刪除</button>
                                    </view>
                                </view>
                            </view>
                        </view>
                        <view class="uni-list-cell">
                            <view class="uni-list-cell-left">
                                車牌號碼:
                            </view>
                            <view class="uni-list-cell-db">
                                <picker @change="bindPickerChange(indexItem, $event)" :value="indexArray[indexItem]" :range="truckList"
                                 range-key="licensePlateNumber" @click="getTruckList(1)">
                                    <view class="uni-input">{{truckList[indexArray[indexItem]].licensePlateNumber}}</view>
                                </picker>
                            </view>
                        </view>
                        <view class="uni-list-cell">
                            <view class="uni-list-cell-left">
                                車輛類型:
                            </view>
                            <view class="uni-list-cell-db">
                                <view class="uni-input">{{truckList[indexArray[indexItem]].truckType}}</view>
                            </view>
                        </view>
                        <view class="uni-list-cell">
                            <view class="uni-list-cell-left">
                                車主姓名:
                            </view>
                            <view class="uni-list-cell-db">
                                <view class="uni-input">{{truckList[indexArray[indexItem]].truckOwner}}</view>
                            </view>
                        </view>
                        <view class="uni-list-cell">
                            <view class="uni-list-cell-left">
                                車主電話:
                            </view>
                            <view class="uni-list-cell-db">
                                <view class="uni-input">{{truckList[indexArray[indexItem]].telephone}}</view>
                            </view>
                        </view>
                        <view class="uni-list-cell">
                            <view class="uni-list-cell-left">
                                行駛證照片:
                            </view>
                            <view class="uni-center" style="background:#FFFFFF; font-size:0;">
                                <image class="image" mode="widthFix" :src="truckList[indexArray[indexItem]].vehicleLicenseImage" :data-src="truckList[indexArray[indexItem]].vehicleLicenseImage"
                                 @tap="previewImage" />
                                </image>
                            </view>
                        </view>
                    </view>
                </view>
                <view style="margin-top: 10rpx; margin-bottom: 10rpx;">
                    <button type="primary"  plain="true" @click="addTruck()">添加車輛</button>
                </view>

                <!-- 申請信息 -->
                <view class="uni-list">
                    <view class="uni-list-cell">
                        <view class="uni-list-cell-left">
                            項目建設單位:
                        </view>
                        <view class="uni-list-cell-db">
                            <input class="uni-input" name="projectConstructionUnit" placeholder="請輸入項目建設單位" />
                        </view>
                    </view>
                    <view class="uni-list-cell">
                        <view class="uni-list-cell-left">
                            負責人:
                        </view>
                        <view class="uni-list-cell-db">
                            <input class="uni-input" name="personInCharge" placeholder="請輸入負責人" />
                        </view>
                    </view>
                    <view class="uni-list-cell">
                        <view class="uni-list-cell-left">
                            負責人電話:
                        </view>
                        <view class="uni-list-cell-db">
                            <input class="uni-input" name="phone" placeholder="請輸入負責人電話" />
                        </view>
                    </view>
                    <view class="uni-list-cell">
                        <view class="uni-list-cell-left">
                            運載物料類型:
                        </view>
                        <view class="uni-list-cell-db">
                            <picker @change="bindPickerChangeType" :value="indexType" :range="materialsTypeList" range-key="itemText" name="materialsType"
                             @click="getMaterialsTypeList">
                                <view class="uni-input">{{materialsTypeList[indexType].itemText}}</view>
                            </picker>
                        </view>
                    </view>
                    <view class="uni-list-cell">
                        <view class="uni-list-cell-left">
                            申請人:
                        </view>
                        <view class="uni-list-cell-db">
                            <input class="uni-input" name="applicant" placeholder="請輸入申請人" />
                        </view>
                    </view>
                    <view class="uni-list-cell">
                        <view class="uni-list-cell-left">
                            申請人電話:
                        </view>
                        <view class="uni-list-cell-db">
                            <input class="uni-input" name="telephone" placeholder="請輸入申請人電話" />
                        </view>
                    </view>
                    <view class="uni-list-cell">
                        <view class="uni-list-cell-left">
                            開始時間:
                        </view>
                        
                        <picker class="uni-list-cell-db"  mode="multiSelector" @change="bindMultiPickerChange" @columnchange="bindMultiPickerColumnChange" :value="multiIndex" :range="multiArray">
                            <input class="uni-input"  :value="startTime" placeholder='請選擇開始時間'/>
                        </picker>
                    </view>
                    <view class="uni-list-cell">
                        <view class="uni-list-cell-left">
                            結束時間:
                        </view>
                        
                        <picker class="uni-list-cell-db"  mode="multiSelector" @change="bindMultiPickerChange1" @columnchange="bindMultiPickerColumnChange" :value="multiIndex" :range="multiArray">
                            <input class="uni-input"  :value="endTime" placeholder='請選擇結束時間'/>
                        </picker>
                    </view>
                    <view class="uni-list-cell">
                        <view class="uni-list-cell-left">
                            起點路線:
                        </view>
                        <view class="uni-list-cell-db">
                            <input class="uni-input" name="startPoint" disabled="true" placeholder="請輸入起點路線" @tap="chooseStartPoint" v-model="startPoint" />
                        </view>
                    </view>
                    <view class="uni-list-cell">
                        <view class="uni-list-cell-left">
                            終點路線:
                        </view>
                        <view class="uni-list-cell-db">
                            <input class="uni-input" name="endPoint" disabled="true" placeholder="請輸入終點路線" @tap="chooseEndPoint" v-model="endPoint" />
                        </view>
                    </view>
                    <view class="uni-list-cell">
                        <view class="uni-list-cell-left" >
                            申請理由:
                        </view>
                        <view class="uni-list-cell-db">
                            <textarea class="textarea-content" name="applicationReason" placeholder="請輸入申請理由及上傳證明材料"></textarea>
                        </view>
                    </view>
                </view>
                <view class="uni-btn-v" v-if="buttonFlag == false">
                    <button form-type="submit" type="primary">保存</button>
                </view>
            </form>
        </view>

        
    </view>
</template>

<script>
    import { postAction } from '../../common/request.js';
    import wPicker from "@/components/w-picker/w-picker.vue";
    var util = require('../../common/util.js');
    var graceChecker = require("../../common/graceChecker.js");
    
    const date = new Date();
    const years = [];
    const months = [];
    const days = [];
    const hours = [];
    const minutes = [];
    //獲取年
    for (let i = 2020; i <= date.getFullYear() + 5; i++) {
      years.push("" + i);
    }
    //獲取月份
    for (let i = 1; i <= 12; i++) {
      if (i < 10) {
        i = "0" + i;
      }
      months.push("" + i);
    }
    //獲取日期
    for (let i = 1; i <= 31; i++) {
      if (i < 10) {
        i = "0" + i;
      }
      days.push("" + i);
    }
    //獲取小時
    for (let i = 0; i < 24; i++) {
      if (i < 10) {
        i = "0" + i;
      }
      hours.push("" + i);
    }
    //獲取分鍾
    for (let i = 0; i < 60; i++) {
      if (i < 10) {
        i = "0" + i;
      }
      minutes.push("" + i);
    }
    export default {
        components: {
            wPicker
        },
        data() {
            return {
                truckList: [{
                    licensePlateNumber: '請選擇車輛'
                }],
                url: {
                    getDictTypeList: "truck/wxApp/getDictTypeList",
                    add: 'truck/wxApp/truckApplication/addOrEdit',
                    getTruckList: 'truck/wxApp/truck/getTruckList',
                },
                truckIdArray: [],
                truckNumberArray: [],
                indexArray: [],
                materialsTypeList: [{
                    itemText: '請選擇運載物料類型'
                }],
                indexType: 0,
                startTime: '',
                endTime: '',
                startPoint: '',
                endPoint: '',
                startPointLongitude: '',
                endPointLongitude: '',
                startPointLatitude: '',
                endPointLatitude: '',
                buttonFlag: false,
                
                multiArray: [years, months, days, hours, minutes],
                multiIndex: [0, 0, 0, 10, 0],
                choose_year: '',
            }
        },
        
        onLoad() {
            this.getTruckList(0);
            this.getMaterialsTypeList();
            //this.choose_year = this.data.multiArray[0][0]
            var date = new Date();
            this.multiIndex = [date.getFullYear() - 2020,date.getMonth(),date.getDate() - 1,0,0]
        },
        methods: {
            bindMultiPickerChange(e) {
                 /* console.log('picker發送選擇改變,攜帶值為', e.detail.value) */
                
                this.multiIndex = e.detail.value
                
                const index = this.multiIndex;
                const year = this.multiArray[0][index[0]];
                const month = this.multiArray[1][index[1]];
                const day = this.multiArray[2][index[2]];
                const hour = this.multiArray[3][index[3]];
                const minute = this.multiArray[4][index[4]];
                // console.log(`${year}-${month}-${day}-${hour}-${minute}`);
                
                this.startTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute
                
                // console.log(this.data.time);
              },
                  
              bindMultiPickerChange1(e){
                  this.multiIndex = e.detail.value
                  
                  const index = this.multiIndex;
                  const year = this.multiArray[0][index[0]];
                  const month = this.multiArray[1][index[1]];
                  const day = this.multiArray[2][index[2]];
                  const hour = this.multiArray[3][index[3]];
                  const minute = this.multiArray[4][index[4]];
                  // console.log(`${year}-${month}-${day}-${hour}-${minute}`);
                  
                  this.endTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute
              },
              //監聽picker的滾動事件
              bindMultiPickerColumnChange(e) {
                  
                /* console.log('修改的列為', e.detail.column, ',值為', e.detail.value); */
                if (e.detail.column == 0) {
                  let choose_year = this.multiArray[e.detail.column][e.detail.value];
                  
                  /* this.setData({
                    
                  }) */
                  this.choose_year = choose_year;
                }
                
                if (e.detail.column == 1) {
                  let num = parseInt(this.multiArray[e.detail.column][e.detail.value]);
                  let temp = [];
                  if (num == 1 || num == 3 || num == 5 || num == 7 || num == 8 || num == 10 || num == 12) { //判斷31天的月份
                    for (let i = 1; i <= 31; i++) {
                      if (i < 10) {
                        i = "0" + i;
                      }
                      temp.push("" + i);
                    }
                    
                      this.multiArray[2] = temp
                   ;
                  } else if (num == 4 || num == 6 || num == 9 || num == 11) { //判斷30天的月份
                    for (let i = 1; i <= 30; i++) {
                      if (i < 10) {
                        i = "0" + i;
                      }
                      temp.push("" + i);
                    }
                    
                      this.multiArray[2] = temp
                    ;
                  } else if (num == 2) { //判斷2月份天數
                    let year = parseInt(this.choose_year);
                    if (((year % 400 == 0) || (year % 100 != 0)) && (year % 4 == 0)) {
                      for (let i = 1; i <= 29; i++) {
                        if (i < 10) {
                          i = "0" + i;
                        }
                        temp.push("" + i);
                      }
                      
                        this.multiArray[2] = temp
                      
                    } else {
                      for (let i = 1; i <= 28; i++) {
                        if (i < 10) {
                          i = "0" + i;
                        }
                        temp.push("" + i);
                      }
                      
                        this.multiArray[2] = temp
                      ;
                    }
                  }
                }
                var data = {
                  multiArray: this.multiArray,
                  multiIndex: this.multiIndex
                };
                data.multiIndex[e.detail.column] = e.detail.value;
                
              },
            
            //查詢車輛列表
            getTruckList(value) {
                let _this = this;
                let parms = {
                    wxUserId: '123',
                };
                postAction(this.url.getTruckList, parms).then(function(res) {
                    if (value == 0) {
                        if (res.records.length > 0) {
                            _this.truckList = res.records;
                            for (let i = 0; i < _this.truckList.length; i++) {
                                _this.truckList[i].vehicleLicenseImage = util.getImgFullUrl(_this.truckList[i].vehicleLicenseImage);
                            }
                            _this.truckIdArray.push(_this.truckList[0].id);
                            _this.truckNumberArray.push(_this.truckList[0].licensePlateNumber);
                            _this.indexArray.push(0);
                        } else {
                            uni.showModal({
                                content: '當前用戶暫無車輛,請前往添加',
                                showCancel: false,
                                success: (res) => {
                                    if (res.confirm) {
                                        uni.navigateTo({
                                            url: '/pages/userInfo/myTruck'
                                        })
                                    }
                                }
                            })
                        }
                    } else if (value == 1) {
                        _this.truckList = res.records;
                        for (let i = 0; i < _this.truckList.length; i++) {
                            _this.truckList[i].vehicleLicenseImage = util.getImgFullUrl(_this.truckList[i].vehicleLicenseImage);
                        }
                    }
                })
            },
            //點擊切換選擇車輛
            bindPickerChange: function(index, e) {
                if (this.truckIdArray.length > 1 && this.truckIdArray.indexOf(this.truckList[e.detail.value].id) != -1) {
                    uni.showToast({
                        title: "車輛已選,請重新選擇",
                        icon: "none"
                    })
                } else {
                    this.truckIdArray.splice(index, 1, this.truckList[e.detail.value].id);
                    this.truckNumberArray.splice(index, 1, this.truckList[e.detail.value].licensePlateNumber);
                    this.indexArray.splice(index, 1, e.detail.value);
                }
            },
            //預覽行駛證照片
            previewImage: function(e) {
                var current = e.target.dataset.src
                uni.previewImage({
                    current: current,
                    urls: [current]
                })
            },
            //繼續添加車輛信息
            addTruck: function() {
                if (this.truckIdArray.length >= this.truckList.length) {
                    return false;
                }
                this.truckIdArray.push(this.truckList[this.indexArray.length].id);
                this.truckNumberArray.push(this.truckList[this.indexArray.length].licensePlateNumber);
                this.indexArray.push(this.indexArray[this.indexArray.length - 1] + 1);
            },
            //移除車輛信息
            removeTruck: function(indexItem) {
                this.truckIdArray.splice(indexItem, 1);
                this.truckNumberArray.splice(indexItem, 1);
                this.indexArray.splice(indexItem, 1);
            },
            //條件查詢運載物料類型
            getMaterialsTypeList() {
                var params = {
                    dictCode: 'materials_type'
                }
                postAction(this.url.getDictTypeList, params).then((res) => {
                    this.materialsTypeList = res;
                })
            },
            //點擊切換運載物料類型
            bindPickerChangeType: function(e) {
                this.indexType = e.detail.value
            },
            
            onCancel() {

            },
            //比較開始時間、結束時間
            comparedTime: function(startTime, endTime){
                if (startTime != "" && endTime != ""){
                    let startDate = this.transferDate(this.transferDate(startTime)).getTime();
                    let endDate = this.transferDate(this.transferDate(endTime)).getTime();
                    return startDate < endDate ? true : false;
                }
            },
            transferDate: function(date) {
                if(typeof date == "string") {
                      return new Date(date.replace(/-/ig, "/"));
                } else {
                      return date;
                }
            },
            
            //選擇起點地圖
            chooseStartPoint: function() {
                uni.chooseLocation({
                    success: (res) => {
                        this.startPointLongitude = res.longitude,
                        this.startPointLatitude = res.latitude,
                        this.startPoint = res.address + res.name
                    }
                })
            },
            //選擇終點地圖
            chooseEndPoint: function() {
                uni.chooseLocation({
                    success: (res) => {
                        this.endPointLongitude = res.longitude,
                        this.endPointLatitude = res.latitude,
                        this.endPoint = res.address + res.name
                    }
                })
            },
            //表單提交
            formSubmit: function(e) {
                //定義表單規則
                var rule = [
                    { name: "projectConstructionUnit", checkType: "string", checkRule: "2,20", errorMsg: "項目建設單位應為2-20字符" },
                    { name: "personInCharge", checkType: "string", checkRule: "2,4", errorMsg: "負責人姓名應為2-4字符" },
                    { name: "phone", checkType: "phoneno", checkRule: "11", errorMsg: "負責人電話應為11位數字" },
                    { name: "applicant", checkType: "string", checkRule: "2,4", errorMsg: "申請人姓名應為2-4字符" },
                    { name: "telephone", checkType: "phoneno", checkRule: "11", errorMsg: "申請人電話應為11位數字" },
                ];

                //進行表單檢查
                var formData = e.detail.value;
                formData.createdBy = '123';//從本地緩存中獲取關注用戶微信openId
                formData.truckId = this.truckIdArray.join(','); //車輛id
                formData.licensePlateNumber = this.truckNumberArray.join(','); //車牌號碼
                formData.materialsType = this.materialsTypeList[formData.materialsType].itemValue; //字典值
                formData.startPointLongitude = this.startPointLongitude;
                formData.startPointLatitude = this.startPointLatitude;
                formData.endPointLongitude = this.endPointLongitude;
                formData.endPointLatitude = this.endPointLatitude;
                formData.passRoute = this.startPoint + ' → ' + this.endPoint;
                formData.correctPassRoute = this.startPoint + ' → ' + this.endPoint;
                formData.correctStartTime = this.startTime;
                formData.correctEndTime = this.endTime;
                var checkRes = graceChecker.check(formData, rule);
                if (checkRes) {
                    if (this.startTime == "") {
                        uni.showToast({
                            title: "請選擇開始時間!",
                            icon: "none"
                        });
                        return false;
                    }
                    if (this.endTime == "") {
                        uni.showToast({
                            title: "請選擇結束時間!",
                            icon: "none"
                        });
                        return false;
                    }
                    if(!this.comparedTime(this.startTime, this.endTime)){
                        uni.showToast({
                            title: "開始時間不大於結束時間!",
                            icon: "none"
                        });
                        return false;
                    }
                    if (this.startPoint == "") {
                        uni.showToast({
                            title: "請選擇起點路線!",
                            icon: "none"
                        });
                        return false;
                    }
                    if (this.endPoint == "") {
                        uni.showToast({
                            title: "請選擇路線!",
                            icon: "none"
                        });
                        return false;
                    }

                    this.buttonFlag = true;
                    postAction(this.url.add, formData).then((res) => {
                        uni.showToast({
                            title: "提交成功!"
                        })
                        setTimeout(function() {
                            uni.navigateTo({
                                url: '/pages/application/myApplication?status=0'
                            })
                        }, 2000)
                    })
                } else {
                    uni.showToast({
                        title: graceChecker.error,
                        icon: "none"
                    });
                }
            },
        }
    }
</script>

<style>
    .image {
        margin-right: 200rpx;
        margin-bottom: 40rpx;
        width: 200rpx;
        height: 200rpx;
        margin-top: 20px;
    }

    .textarea-content {
        height: 180rpx;
        width: 490rpx;
        margin-top: 130rpx;
    }
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM