preface

This paper is the use of mpVue + small program cloud development and construction of mini micro channel small program, small program loading process will be slightly slower, if there is any problem, please kindly advise. The small program is divided into three parts: 1. The home page is mainly to display the published content; 2. Keep a diary is an item for adding data. 3. The details page is the specific details of the content

Like a small partner move your hands to a small star oh, thank you!! Applets source code

Small program TWO-DIMENSIONAL code

Home page

First look at the home page renderings, the top is a round broadcast this round is to get the number of preview number of the first published picture, the middle part is the content display area all, the latest, mine.

// index.vueMethods: {// Jump details
    navigateTo (id) {
      wx.navigateTo({
        url: '.. /diaryDetail/main? id=' + id
      })
    },
    // Toggle all, latest, mine
    switechNav (index) {
      this.isActive = index
      if (index === 0) {
        this.getDiaryList()
      }
      if (index === 1) {
        this.getNewList()
      }
      if (index === 2) {
        this.getOpenId()
      }
    },
    // Most recently released, top 10 in chronological order
    getNewList () {
      const that = this
      wx.showLoading({
        title: 'Loading'
      })
      wx.cloud.callFunction({
        name: 'diaryList'
      }).then(res= > {
        let infoList = res.result.data.reverse()
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
        that.diaryList = infoList.slice(0.10)})},// Get self-published
    getMyList () {
      const that = this
      const db = wx.cloud.database()
      const diary = db.collection('diary')
      wx.showLoading({
        title: 'Loading'
      })
      diary.where({
        _openid: that.openId
      }).get({
        success: function (res) {
          setTimeout(function () {
            wx.hideLoading()
          }, 2000)
          if (res.data.length === 0) {
            toast('You have not posted an article diary for the time being'.'none')
          }
          that.diaryList = res.data.reverse()
        }
      })
    },
    // Get the list of diaries from the cloud function
    getDiaryList () {
      const that = this
      wx.showLoading({
        title: 'Loading'
      })
      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})},/ / get the openid
    getOpenId () {
      const that = this
      wx.cloud.callFunction({
        name: 'user'
      }).then(res= > {
        that.openId = res.result.OPENID
        that.getMyList()
      })
    }
}
Copy the code

Tool function

Utility functions in utils/index.js, do time formatting and pop up prompts

function addZero (n) {
  return n > 10 ? n : '0' + n
}
// Toast pop-up prompt
export function toast (title = 'success', icon = 'success', duration = 2000) {
  wx.showToast({
    title: title,
    icon: icon,
    duration: duration
  })
}
// Time formatting
export function getNowFormatDate () {
  const now = new Date(a)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 + The '-' + month + The '-' + day + ' ' + hh + ':' + mm + ':' + ss
  return timer
}

export default {
  toast,
  getNowFormatDate
}
Copy the code

Details page

Show the details of the content, the top rotation is the picture uploaded by the author, you can click to view the original picture, for the diary like, as well as the comment function

// diaryDetail.vue
methods: {
    $this.$root.$mp.query
    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
      })
    },
  / / thumb up
    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('No more likes! '.'none')}})},// Add a likes person so that you can determine whether to repeat the likes
    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 is a thumbs up
        }
      }).then(res= > {
        that.isAnimate = true
        that.changeDZCount(_id)
      })
    },
    // Call the "like cloud" function to increase the number of likes
    changeDZCount (id) {
      const that = this
      wx.cloud.callFunction({
        name: 'dianzan'.data: {
          _id: id
        }
      }).then(res= > {
        toast('Thank you for your recognition! '.'none')
        that.getDiaryDetail(id)
      })
    },
    // Determine whether the reader has already liked the article. If so, the page will turn red
    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}}})},// Get comments
    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()
        }
      })
    },
    // Add a comment
    addComment () {
      if (this.content === ' ') {
        toast('Please enter comments'.'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, / / the body of the id
          user: that.userInfo, // User information
          content: that.content, // Comment content
          time: getNowFormatDate() // Comment time
        }
      }).then(res= > {
        that.contentCount = 0
        that.getComment(this.$root.$mp.query.id)
      })
    },
    // Determine if the user has posted a comment
    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('Published successfully')
          that.content = ' '
          return false
        }
        toast('Can't comment twice! '.'none')})},// Bind comment words
    handleContentInput (e) {
      this.contentCount = e.target.value.length
    },
    // Make a comment
    onGotUserInfo (e) {
      this.userInfo = e.target.userInfo
      this.getIsComment()
    },
    // Call wechat API wx.previewImage
    handleImagePreview (e) {
      let idx = e.target.dataset.idx
      let images = this.detailImgs
      wx.previewImage({
        current: images[idx],
        urls: images
      })
    }
}
Copy the code

Write a diary

Save temporary images generated by wx.chooseImage() to wechat cloud storage, mainly using the wx.cloud.uploadfile () method

// write.vue
methods: {
    // Upload the image and save the temporary image to cloud storage
    chooseImage () {
      const that = this
      wx.chooseImage({
        count: 9.sizeType: ['original'.'compressed'].sourceType: ['album'.'camera'].success: function (res) {
          // Upload the selected image to the cloud storage
          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)}})}})},// Limit the title word count
    handleTitleInput (e) {
      this.titleCount = e.target.value.length
    },
    // Limit the title word count
    handleContentInput (e) {
      this.contentCount = e.target.value.length
    },
    // Full screen preview image
    handleImagePreview (e) {
      console.log(e)
      let idx = e.target.dataset.idx
      let images = this.imagesList
      wx.previewImage({
        current: images[idx], // Index of the current preview image
        urls: images // All images to preview})},// Remove unwanted graphs
    removeImage (e) {
      const that = this
      const idx = e.target.dataset.idx // The index of the image to be removed
      wx.showModal({
        title: 'tip'.content: 'Are you sure you want to delete this photo? ',
        success (res) {
          if (res.confirm) {
            that.imagesList.splice(idx, 1)
            toast('Deleted successfully')}else if (res.cancel) {
            console.log('User hit Cancel')}}})},// Publish articles
    onGotUserInfo (e) {
      if (this.title === ' ') {
        toast('Please enter article title'.'none')
        return false
      }
      if (this.content === ' ') {
        toast('Please enter the content of the article'.'none')
        return false
      }
      if (this.imagesList.length === 0) {
        toast('You haven't uploaded a picture yet'.'none')
        return false
      }
      this.userInfo = e.target.userInfo
      this.getOpenId()
    },
    // Write data to the database
    sendMessage () {
      const that = this
      const db = wx.cloud.database()
      const diary = db.collection('diary')
      diary.add({
        data: {
          title: that.title, // Text title
          content: that.content, // The content of the text
          imagesList: that.imagesList, // Upload the image list
          avatarUrl: that.userInfo.avatarUrl, / / avatar
          nickname: that.userInfo.nickName, / / name
          preview: 0./ / the preview
          fabulous: 0./ / thumb up
          creatTime: getNowFormatDate()
        }
      }).then(res= > {
        toast('Released successfully')
        that.title = that.content = ' '
        that.titleCount = that.contentCount = 0
        that.imagesList = []
      })
    },
}
Copy the code

At the end of

To use cloud development, you need to put the following code in the root directory SRC /main.js

wx.cloud.init({
  env: 'Cloud Development Environment ID'
})
Copy the code

Json file to add “cloud”: true to tell small programs to use cloud development, project. Config. json file to add “cloudfunctionRoot”: “static/functions/” to specify the directory to store cloud functions