mpVue + 云开发微信小程序之旅

栏目: 编程工具 · 发布时间: 6年前

内容简介:本文是使用mpVue + 小程序云开发构建的mini型的微信小程序,小程序加载过程会稍微比较慢,如存在问题望各路大神指教。 小程序分为三个部分:1. 首页主要是展示发布的内容;2. 写日记是提供添加数据的项;3. 详情页是浏览内容正文的具体详情喜欢的小伙伴动动您的小手给个小星星哦,谢谢!!小程序二维码

本文是使用mpVue + 小程序云开发构建的mini型的微信小程序,小程序加载过程会稍微比较慢,如存在问题望各路大神指教。 小程序分为三个部分:1. 首页主要是展示发布的内容;2. 写日记是提供添加数据的项;3. 详情页是浏览内容正文的具体详情

喜欢的小伙伴动动您的小手给个小星星哦,谢谢!! 小程序源码

小程序二维码

mpVue + 云开发微信小程序之旅

首页

先看首页效果图,顶部是一个轮播 此轮播是获取预览人数排名第一个的发布的图片 ,中间部分是内容展示区 全部,最新,我的

mpVue + 云开发微信小程序之旅

直接上代码吧

// index.vue
methods: {
    // 跳转详情
    navigateTo (id) {
      wx.navigateTo({
        url: '../diaryDetail/main?id=' + id
      })
    },
    // 切换 全部, 最新, 我的
    switechNav (index) {
      this.isActive = index
      if (index === 0) {
        this.getDiaryList()
      }
      if (index === 1) {
        this.getNewList()
      }
      if (index === 2) {
        this.getOpenId()
      }
    },
    // 最近发布的,按时间 排序 前10条
    getNewList () {
      const that = this
      wx.showLoading({
        title: '加载中'
      })
      wx.cloud.callFunction({
        name: 'diaryList'
      }).then(res => {
        let infoList = res.result.data.reverse()
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
        that.diaryList = infoList.slice(0, 10)
      })
    },
    // 获取自己发布的
    getMyList () {
      const that = this
      const db = wx.cloud.database()
      const diary = db.collection('diary')
      wx.showLoading({
        title: '加载中'
      })
      diary.where({
        _openid: that.openId
      }).get({
        success: function (res) {
          setTimeout(function () {
            wx.hideLoading()
          }, 2000)
          if (res.data.length === 0) {
            toast('您暂时没有发布文章日记', 'none')
          }
          that.diaryList = res.data.reverse()
        }
      })
    },
    // 通过云函数获取日记的list
    getDiaryList () {
      const that = this
      wx.showLoading({
        title: '加载中'
      })
      wx.cloud.callFunction({
        name: 'diaryList'
      }).then(res => {
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
        let infoList = res.result.data
        that.diaryList = infoList.sort(function (a, b) {
          return b.preview - a.preview
        })
        that.imgUrls = that.diaryList[0].imagesList
      })
    },
    // 获取openid
    getOpenId () {
      const that = this
      wx.cloud.callFunction({
        name: 'user'
      }).then(res => {
        that.openId = res.result.OPENID
        that.getMyList()
      })
    }
}
复制代码

工具函数

工具函数在 utils/index.js,做时间格式化和弹出提示

function addZero (n) {
  return n > 10 ? n : '0' + n
}
// toast 弹出提示
export function toast (title = '成功', icon = 'success', duration = 2000) {
  wx.showToast({
    title: title,
    icon: icon,
    duration: duration
  })
}
// 时间格式化
export function getNowFormatDate () {
  const now = new Date()
  const year = now.getFullYear()
  const month = addZero(now.getMonth() + 1)
  const day = addZero(now.getDate())
  const hh = addZero(now.getHours())
  const mm = addZero(now.getMinutes())
  const ss = addZero(now.getSeconds())
  const timer = year + '-' + month + '-' + day + ' ' + hh + ':' + mm + ':' + ss
  return timer
}

export default {
  toast,
  getNowFormatDate
}
复制代码

详情页

展示内容详情,顶部轮播是作者上传的图片,可以点击查看原图,有为日记点赞,以及评论功能

mpVue + 云开发微信小程序之旅
// diaryDetail.vue
methods: {
    // id 是文章id通过首页跳转传过来 page页面可以用 this.$root.$mp.query.id 获取
    getDiaryDetail (id) {
      const that = this
      const db = wx.cloud.database()
      const diary = db.collection('diary')
      diary.doc(id).get().then(res => {
        that.detailInfo = res.data
        that.detailImgs = res.data.imagesList
      })
    },
  // 点赞
    dianZan () {
      const that = this
      const db = wx.cloud.database()
      const _id = this.$root.$mp.query.id
      const dianzan = db.collection('dianzan')
      dianzan.where({
        textId: _id,
        _openid: that.openId
      }).get({
        success: function (res) {
          if (res.data.length === 0) {
            that.addDZ()
            return false
          }
          toast('不能重复点赞哦!', 'none')
        }
      })
    },
    // 添加点赞人,以便可以判断是否重复点赞
    addDZ () {
      const that = this
      const _id = this.$root.$mp.query.id
      const db = wx.cloud.database()
      const dianzan = db.collection('dianzan')
      dianzan.add({
        data: {
          textId: _id, // 文字id
          isZan: 1 // 1 为点赞
        }
      }).then(res => {
        that.isAnimate = true
        that.changeDZCount(_id)
      })
    },
    // 调用点赞云函数,自增点赞数
    changeDZCount (id) {
      const that = this
      wx.cloud.callFunction({
        name: 'dianzan',
        data: {
          _id: id
        }
      }).then(res => {
        toast('谢谢您的认可哦!', 'none')
        that.getDiaryDetail(id)
      })
    },
    // 判断阅读的人是否对这篇文章已经点过赞,如果点过赞进入页面心直接变红
    getZan () {
      const that = this
      const db = wx.cloud.database()
      const _id = this.$root.$mp.query.id
      const dianzan = db.collection('dianzan')
      dianzan.where({
        textId: _id,
        _openid: that.openId
      }).get({
        success: function (res) {
          if (res.data.length) {
            that.isAnimate = true
          }
        }
      })
    },
    // 获取评论
    getComment (id) {
      const that = this
      const db = wx.cloud.database()
      const comment = db.collection('comment')
      comment.where({
        textId: id
      }).get({
        success: function (res) {
          that.commentList = res.data.reverse()
        }
      })
    },
    // 添加评论
    addComment () {
      if (this.content === '') {
        toast('请输入评论内容', 'none')
        return false
      }
      const that = this
      const db = wx.cloud.database()
      const comment = db.collection('comment')
      comment.add({
        data: {
          textId: this.$root.$mp.query.id, // 正文id
          user: that.userInfo, // 用户信息
          content: that.content, // 评论内容
          time: getNowFormatDate() // 评论时间
        }
      }).then(res => {
        that.contentCount = 0
        that.getComment(this.$root.$mp.query.id)
      })
    },
    // 判断用户是否发表过评论
    getIsComment () {
      const that = this
      const db = wx.cloud.database()
      const comment = db.collection('comment')
      comment.where({
        _openid: that.openId,
        textId: this.$root.$mp.query.id
      }).get().then(res => {
        if (res.data.length === 0) {
          that.addComment()
          toast('发表成功')
          that.content = ''
          return false
        }
        toast('不能重复发表评论哦!', 'none')
      })
    },
    // 绑定评论字数
    handleContentInput (e) {
      this.contentCount = e.target.value.length
    },
    // 发表评论
    onGotUserInfo (e) {
      this.userInfo = e.target.userInfo
      this.getIsComment()
    },
    // 轮播图 全屏预览图片 调用微信API wx.previewImage
    handleImagePreview (e) {
      let idx = e.target.dataset.idx
      let images = this.detailImgs
      wx.previewImage({
        current: images[idx],
        urls: images
      })
    }
}
复制代码

写日记

将 wx.chooseImage() 生成的临时图片保存到微信云存储,主要掉用 wx.cloud.uploadFile()方法

mpVue + 云开发微信小程序之旅
// write.vue
methods: {
    // 上传图片,并将临时图片保存到云存储中
    chooseImage () {
      const that = this
      wx.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          // 将选择的图片上传到云存储
          for (let i = 0; i < res.tempFilePaths.length; i++) {
            const filePath = res.tempFilePaths[i]
            const name = Math.random() * 1000000
            const cloudPath = name + filePath.match(/\.[^.]+?$/)[0]
            wx.cloud.uploadFile({
              cloudPath,
              filePath,
              success: res => {
                let images = that.imagesList.concat(res.fileID)
                that.imagesList = images.length <= 9 ? images : images.slice(0, 9)
              }
            })
          }
        }
      })
    },
    // 限制标题字数
    handleTitleInput (e) {
      this.titleCount = e.target.value.length
    },
    // 限制标题字数
    handleContentInput (e) {
      this.contentCount = e.target.value.length
    },
    // 全屏预览图片
    handleImagePreview (e) {
      console.log(e)
      let idx = e.target.dataset.idx
      let images = this.imagesList
      wx.previewImage({
        current: images[idx], // 当前预览的图片索引
        urls: images // 所有要预览的图片
      })
    },
    // 移除不想要的图
    removeImage (e) {
      const that = this
      const idx = e.target.dataset.idx // 当前需要移除的图片索引
      wx.showModal({
        title: '提示',
        content: '您确定删除这张照片吗?',
        success (res) {
          if (res.confirm) {
            that.imagesList.splice(idx, 1)
            toast('删除成功')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
    // 发布文章
    onGotUserInfo (e) {
      if (this.title === '') {
        toast('请输入文章标题', 'none')
        return false
      }
      if (this.content === '') {
        toast('请输入文章内容', 'none')
        return false
      }
      if (this.imagesList.length === 0) {
        toast('您还没上传图片', 'none')
        return false
      }
      this.userInfo = e.target.userInfo
      this.getOpenId()
    },
    // 往数据库里写数据
    sendMessage () {
      const that = this
      const db = wx.cloud.database()
      const diary = db.collection('diary')
      diary.add({
        data: {
          title: that.title, // 正文标题
          content: that.content, // 正文内容
          imagesList: that.imagesList, // 上传图片 list
          avatarUrl: that.userInfo.avatarUrl, // 头像
          nickname: that.userInfo.nickName, // 名字
          preview: 0, // 预览数
          fabulous: 0, // 点赞数
          creatTime: getNowFormatDate()
        }
      }).then(res => {
        toast('发布成功')
        that.title = that.content = ''
        that.titleCount = that.contentCount = 0
        that.imagesList = []
      })
    },
}
复制代码

末尾

在使用云开发中需要将如下代码放到根目录的 src/main.js中

wx.cloud.init({
  env: '云开发环境ID'
})
复制代码

app.json 文件下添加 "cloud": true 告诉小程序使用云开发, project.config.json文件下添加 "cloudfunctionRoot": "static/functions/", 指定存放云函数的目录


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Clean Architecture

Clean Architecture

Robert C. Martin / Prentice Hall / 2017-9-20 / USD 34.99

Practical Software Architecture Solutions from the Legendary Robert C. Martin (“Uncle Bob”) By applying universal rules of software architecture, you can dramatically improve developer producti......一起来看看 《Clean Architecture》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具