美文网首页
从零开始写一个简单的小程序

从零开始写一个简单的小程序

作者: silentsvv | 来源:发表于2017-08-10 02:02 被阅读0次

    小程序注册

    • 小程序注册
      小程序相关注册信息可以在这里找到,我注册的也是个人小程序。

    每日任务小程序


    我的项目结构

    index页面是登录入口,main是主页面,done和fail是已完成和失败页面。

    Index页面

    index.wxml

    <view class="container">
        <view>
            <image class="user-avatar" src="{{userData.avatarUrl}}"></image>
        </view>
        <view class="user-content">
            <text>你好,{{userData.nickName}}</text>
        </view>
        <view  class="user-btn">
            <button size="default" bindtap="start">开始</button>
        </view>
    </view>
    

    index.wxml内容, userData是使用微信的API获取的用户信息。
    index.js

    Page({
      data: {
        userData: {}
      },
      start: ()=> {
        wx.redirectTo({
          url: '/pages/main/main'
        })
      },
      onLoad(){
        wx.getUserInfo({
          success: (res) => {
            var userInfo = res.userInfo
            var nickName = userInfo.nickName
            var avatarUrl = userInfo.avatarUrl
            var gender = userInfo.gender //性别 0:未知、1:男、2:女
            var province = userInfo.province
            var city = userInfo.city
            var country = userInfo.country
    
            this.setData({
              userData: {
                userInfo,
                nickName,
                avatarUrl,
                gender,
                province,
                city,
                country
              }
            })
          }
        })
      }
    })
    

    index.wxss

    .container {
      display: flex;
      height: 100%;
      width: 100%;
      flex-direction: column;
      align-items: center;
      background: #6CA8E3;
    }
    
    .user-avatar {
      margin-top: 200rpx;
      width: 200rpx;
      height: 200rpx;
      border-radius: 50%;
    }
    
    .user-content {
      margin-top: 200rpx;
    }
    
    .user-content text {
      font-size: 22px;
      color: #fff;
    }
    
    .user-btn {
      margin-top: 300rpx;
      width: 150px;
    }
    
    .user-btn button {
      background-color: #FAFB8D;
      color: #333;
    }
    

    注:要看到index页面,需要在app.json里面配置index的页面入口
    app.json

    {
      "pages": [
        "pages/index/index"
      ],
      "window": {
        "navigationBarBackgroundColor": "#6CA8E3" //导航颜色
      }
    }
    

    app.wxss

    page {
      width: 100%;
      height: 100%;
      font-family: '微软雅黑','Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
    }
    
    
    完成后的样子

    main页面

    main.wxml

    <import src="../template/task/task"/>
    <import src="../template/pop/pop"/>
    <view class="main">
      <view class="task-list">
        <view class="task" wx:for="{{taskData}}">
          <template is="task" data="{{item,now}}"></template>
        </view>
      </view>
      <view class="is-empty" wx:if="{{!taskData.length}}">
        <text>任务为空</text>
      </view>
      <view class="add-task">
        <button bindtap="showPop">点击添加</button>
      </view>
      <view class="pop-wrap" wx:if="{{isShow}}">
        <template is="pop" data="{{target,now}}"></template>
      </view>
      <view class="footer-block"></view>
      <view class="footer">
        <view class="footer-left" bindtap="switchDone">已完成</view>
        <view class="footer-right" bindtap="switchFail">未完成</view>
      </view>
    </view>
    

    main.wxss

    @import "../template/task/task.wxss";
    @import "../template/pop/pop.wxss";
    
    /*页面设置*/
    .main {
      width: 100%;
      height: 100%;
      background-color: #f7f7f7;
      padding-top: 1px;
    }
    
    /*添加按钮*/
    .main .add-task {
      display: flex;
      flex-direction: row;
      justify-content: center;
      margin-top: 40rpx;
      width: 100%;
    }
    
    .main .add-task button {
      width: 350rpx;
      color: #fff;
      background-color: #169BD5;
    }
    
    /*底部导航条*/
    .main .footer {
      position:fixed;
      bottom: 0;
      display: flex;
      flex-direction: row;
      width: 100%;
      height: 120rpx;
      font-size: 16px;
      background: #fff;
      box-shadow: -1px 1px 6px #ccc;
      z-index: 1;
    }
    
    .main .footer .footer-left,
    .main .footer .footer-right {
      text-align: center;
      line-height: 120rpx;
      width: 50%;
    }
    
    .main .footer .footer-left {
      border-right: 1px solid #f2f2f2;
    }
    
    .footer-block {
      height: 140rpx;
    }
    

    main.js

    Page({
      data: {
        isShow: false,
        taskData: [],
        target: "",
        now: ""
      },
    
      //显示弹窗时设置当前时间
      onShow () {
        let data = wx.getStorageSync("taskData");
        let date = new Date();
        let hour = date.getHours();
        let min = date.getMinutes();
        let now = hour + ":" + min;
        this.setData({
          taskData: data,
          now: now
        })
      },
      
      //显示弹窗,并设置目标时间为一小时后
      showPop (event) {
        let date = new Date();
        date.setTime(date.getTime() + 60 * 60 * 1000);
        let hour = date.getHours();
        let min = date.getMinutes();
        let target = hour + ":" + min;
    
        this.setData({
          isShow: true,
          target: target
        })
      },
    
      //改变时间
      bindTimeChange (event) {
        let newTime = event.detail.value;
        this.setData({
          target: newTime
        })
      },
    
      //取消添加任务
      cancel (event) {
        this.setData({
          isShow: false
        })
      },
    
      //完成任务
      finish (event) {
        let idx;
        let old = this.data.taskData.find((data,index) => {
          if(data.id === event.target.dataset.id){
            idx = index;
            return data
          }
        })
        if(old === undefined) {
          console.log("完成失败")
        }else {
          let data = this.data.taskData;
          data.splice(idx,1);
          this.setData({
            taskData: data,
          })
          wx.setStorageSync("taskData", data);
          old.type = "finish";
          let taskData = wx.getStorageSync('finish')||[];
            if(taskData.length != 0) {
              let newData = taskData.concat(old);
              wx.setStorageSync("finish", newData);
            }else {
              let arr =[];
              arr.push(old);
              wx.setStorageSync("finish", arr);
            }
          }
          wx.showToast({
            title: '已完成',
            icon: 'success',
            duration: 500
          })
        },
        
      //未完成任务
      unfinished (event) {
        let idx;
        let old = this.data.taskData.find((data, index) => {
          if (data.id === event.target.dataset.id) {
            idx = index;
            return data
          }
        })
        if (old === undefined) {
          console.log("完成失败")
        } else {
          let data = this.data.taskData;
          data.splice(idx, 1);
          this.setData({
            taskData: data,
          })
          wx.setStorageSync("taskData", data);
          old.type = "unfinished";
          let taskData = wx.getStorageSync('unfinished') || [];
          if (taskData.length != 0) {
            let newData = taskData.concat(old);
            wx.setStorageSync("unfinished", newData);
          } else {
            let arr = [];
            arr.push(old);
            wx.setStorageSync("unfinished", arr);
          }
        }
        wx.showToast({
          title: '成功添加至未完成',
          icon: 'success',
          duration: 500
        })
      },
    
      //提交任务
      formSubmit (event) {
        let newData;
        console.log(this.data.taskData)
        if (this.data.taskData.length == 0){
          newData = [];
        }else {
          newData = this.data.taskData;
        }
        let name = event.detail.value.taskName;
        let time = event.detail.value.taskTime;
        let level = !!event.detail.value.taskLevel;
        let date = new Date();
        let day = date.getDate();
        let month = date.getMonth() + 1;
        let year = date.getFullYear();
        let hour = date.getHours();
        let min = date.getMinutes();
        let sec = date.getSeconds();
        let random = Math.floor(Math.random() * 10000);
        let id ="0" + year + month + day + hour + min + sec + random;
        if(!name) {
          wx.showToast({
            title: '请填写任务',
            icon: 'loading',
            duration: 300
          })
          return false;
        }
        newData.push({
          id: id,
          task: name,
          time: time,
          isUgrent: level
        })
        this.setData({
          taskData:newData,
          isShow: false
        })
        wx.setStorageSync("taskData", newData);
      },
    
      //跳转到已完成页面
      switchDone: () => {
        wx.navigateTo({
          url: '/pages/done/done'
        })
      },
    
      //跳转到未完成页面
      switchFail: () => {
        wx.navigateTo({
          url: '/pages/fail/fail'
        })
      }
    })
    

    大家可能发现了一二行的import,这是我引用的两个模板页task和pop

    template
    要使用template需要声明是哪一个
    pop模板
    <template name="pop">
      <form bindsubmit="formSubmit">
        <view class="pop animated bounceInLeft">
          <view class="pop-title">
            <text>添加任务</text>
          </view>
          <view class="pop-form">
            <view class="form-task line">
              <text>任务</text>
              <input type="text" name="taskName" placeholder="请输入填写任务" bindchange="name"/>
            </view>
            <view class="form-time line">
              <text>时间</text>
              <picker mode="time" name="taskTime" value="{{target}}" start="{{now}}" end="24:00" bindchange="bindTimeChange">
                <view class="picker">
                  {{target}}
                </view>
              </picker>
            </view>
            <view class="form-type line">
              <text>紧急</text>
                <switch name="taskLevel"/>
            </view>
            <view class="form-btn">
              <button class="done" form-type="submit">确定</button>
              <button class="fail" bindtap="cancel">取消</button>
            </view>
            <view class="task-info">
              <text>注:默认时间为一小时</text>
            </view>
          </view>
        </view>
      </form>
    </template>
    

    pop.wxss

    /*弹窗*/
    .pop-wrap {
      position: fixed;
      display: flex;
      flex-direction: column;
      justify-content: center;
      height: 100%;
      width: 100%;
      top: 0;
      left: 0;
      background-color: rgba(0, 0, 0, 0.3);
      z-index: 99;
    }
    
    .pop-wrap .pop {
      width: 680rpx;
      height: 800rpx;
      margin: -100rpx auto 0 auto;
      border-radius: 20rpx;
      background: #fff;
    }
    
    .pop-wrap .pop .pop-title{
      display: block;
      text-align: center;
      background: #6CA8E3;
      padding: 20rpx 0;
      border-radius: 20rpx 20rpx 0 0;
      color: #fff;
    }
    
    .pop-wrap .pop .pop-form .form-task,
    .pop-wrap .pop .pop-form .form-time,
    .pop-wrap .pop .pop-form .form-type {
      position: relative;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 140rpx;
    }
    
    .pop-wrap .pop .pop-form .form-task text,
    .pop-wrap .pop .pop-form .form-time text,
    .pop-wrap .pop .pop-form .form-type text {
      display: flex;
      flex-direction: row;
      justify-content: center;
      width: 30%;
    }
    
    .pop-wrap .pop .pop-form .form-time picker,
    .pop-wrap .pop .pop-form .form-type switch {
      display: flex;
      flex-direction: row;
      justify-content: center;
      width: 70%;
    }
    
    .pop-wrap .pop .pop-form .form-task input {
      border: 1px solid #ccc;
      border-radius: 10rpx;
      margin-right: 10%;
      padding-left: 20rpx;
      height: 68rpx;
    }
    
    .pop-wrap .pop .pop-form .form-btn {
      margin-top: 20rpx;
      display: flex;
      flex-direction: column;
      width: 100%;
      align-items: center;
    }
    
    .pop-wrap .pop .pop-form .form-btn button {
      margin-top: 20rpx;
      color: #fff;
      width: 240rpx;
      height: 80rpx;
      font-size: 16px;
      line-height: 80rpx;
    }
    
    .pop-wrap .pop .pop-form .task-info {
      margin-top: 20rpx;
      text-align: center;
      font-size: 22rpx;
      color: #666;
    }
    

    task.wxml

    <template name="task">
      <view class="task-left">
        <view class="task-detail">
          <text>任务</text>
          <view>
            <text class="blod">{{item.task}}</text>
          </view>
        </view>
        <view class="task-time">
          <text>时间</text>
          <view>
            <text class="blod">{{item.time}}</text>
          </view>
        </view>
      </view>
      <view class="task-right">
        <view class="task-level">{{item.time>now?item.isUgrent?"紧急":
        "正常":"已失败"}}</view>
        <view class="task-btn">
          <block wx:if="{{item.type == undefined}}">
            <button size="mini" class="done" bindtap="finish" data-id="{{item.id}}" disabled="{{item.time>now ?false:true}}">完成</button>
            <button size="mini" class="fail" bindtap="unfinished" data-id="{{item.id}}">失败</button>
          </block>
          <block wx:elif="{{item.type == 'unfinished'}}">
            <button size="mini" class="done" bindtap="restart" data-id="{{item.id}}">重做</button>
            <button size="mini" class="fail" bindtap="deleteUnFin" data-id="{{item.id}}">删除</button>
          </block>
          <block wx:elif="{{item.type == 'finish'}}">
            <button size="mini" class="done" bindtap="deleteFin" data-id="{{item.id}}">删除</button>
          </block>
        </view>
      </view>
    </template>
    

    task.wxss

    /*任务列表样式*/
    .task-list .task {
      display: flex;
      flex-direction: row;
      justify-content: center;
      width: 640rpx;
      height: 300rpx;
      margin: 20rpx auto 0 auto;
      padding: 40rpx;
      font-size: 16px;
      border: 1px solid #ccc;
      border-radius: 20rpx;
      box-shadow: 1px 3px 6px #ccc;
      background: #fff;
    }
    
    .task-list .task .task-left,
    .task-list .task .task-right {
      display: flex;
      flex-direction: column;
      justify-content: center;
      width: 100%;
    }
    
    .task-list .task .task-left .task-detail,
    .task-list .task .task-left .task-time {
      margin: 20rpx 0;
    }
    
    .task-list .task .task-right {
       align-items: flex-end;
    }
    
    .task-level {
      font-size: 26px;
      font-weight: 600;
      margin-bottom: 40rpx;
    }
    
    .task-list .task .task-right .task-btn button{
      display: block;
      margin-top: 10rpx;
      width: 150rpx;
      color: #fff;
    }
    

    template页面需要用name来声明, 引用也需要isimport相关页面,css页面也需要@import 相关页面。
    注:模板的数据需要来使用data引入
    main的js页面,data是用来提供数据的,onShow、onHide等则是官方提供的函数方法,其他的都是我设置的触发事件函数,
    如需要点击触发,在样式里写上bindtap样式(还有catch等其他触发方式)。
    wx:if是根据设置的变量来控制元素的显示,如果需要事件触发改变数据需要使用this.setData()来改变数据,直接使用this.data.isShow = false是不行的。

    done和fail页面

    done.wxml

    <import src="../template/task/task"/>
    <view class="main">
      <view class="task-list">
        <view class="task" wx:for="{{doneList}}">
          <template is="task" data="{{item}}"></template>
        </view>
      </view>
      <view class="is-empty" wx:if="{{!doneList.length}}">
        <text>任务为空</text>
      </view>
    </view>
    

    done.wxss

    @import "../template/task/task.wxss";
    
    /*页面设置*/
    .main {
      width: 100%;
      height: 100%;
      background-color: #f7f7f7;
      padding-top: 1px;
    }
    

    done.js

    Page({
    
      /**
       * 页面的初始数据
       */
      data: {
        doneList:[]
      },
    
      onShow: function () {
        let data = wx.getStorageSync('finish');
        this.setData({
          doneList: data
        })
      },
      deleteFin(event) {
        let taskData = wx.getStorageSync('finish') || [];
        let idx = taskData.findIndex((data) => {
          data.id === event.target.dataset.id
        })
        if (idx === undefined) {
          console.log("完成失败")
        } else {
          taskData.splice(idx, 1);
          wx.setStorageSync("finish", taskData);
          this.setData({
            doneList: taskData
          })
        }
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 500
        })
      }
      
    })
    

    fail.wxml

    <import src="../template/task/task"/>
    <view class="main">
      <view class="task-list">
        <view class="task" wx:for="{{doneList}}">
          <template is="task" data="{{item,test}}"></template>
        </view>
      </view>
      <view class="is-empty" wx:if="{{!doneList.length}}">
        <text>任务为空</text>
      </view>
    </view>
    

    fail.wxss

    @import "../template/task/task.wxss";
    
    /*页面设置*/
    .main {
      width: 100%;
      height: 100%;
      background-color: #f7f7f7;
      padding-top: 1px;
    }
    

    fail.js

    Page({
      data: {
        doneList: []
      },
      onShow: function () {
        let data = wx.getStorageSync('unfinished');
        this.setData({
          doneList: data
        })
      },
      deleteUnFin (event) {
        let taskData = wx.getStorageSync('unfinished') || [];
        let idx = taskData.findIndex((data) => {
          data.id === event.target.dataset.id
        })
        if (idx === undefined) {
          console.log("完成失败")
        } else {
          taskData.splice(idx, 1);
          wx.setStorageSync("unfinished", taskData);
          this.setData({
            doneList: taskData
          })
        }
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 500
        })
      },
      restart (event) {
        let taskData = wx.getStorageSync('unfinished') || [];
        let idx;
        let data = taskData.find((data,index) => {
          if(data.id === event.target.dataset.id) {
            idx = index;
            return data;
          }
        })
        if (data === undefined) {
          console.log("完成失败")
        } else {
          let restart = taskData.splice(idx, 1)[0];
          wx.setStorageSync("unfinished", taskData);
          let newData = wx.getStorageSync("taskData")|| [];
          let date = new Date();
          date.setTime(date.getTime() + 60*60*1000);
          let time = date.getHours() + ":" + date.getMinutes();
          delete (restart.type);
          restart.time = time;
          newData.push(restart);
          wx.setStorageSync("taskData", newData)
          this.setData({
            doneList: taskData
          })
        }
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 500
        })
      }
    })
    

    done页面和fail页面相似。

    结语


    导航条等设置可以在json文件里设置。
    相关代码可以在我的 github上查看相关代码。

    相关文章

      网友评论

          本文标题:从零开始写一个简单的小程序

          本文链接:https://www.haomeiwen.com/subject/xnecrxtx.html