Copyright belongs to the author. Commercial reprint please contact roberthuang for authorization, non-commercial reprint please note the source [be sure to retain the full text, do not delete].


Do not use open source code for commercial purposes!

directory

preface

The preparatory work

Project Structure Introduction

The page is introduced

Introduction to Cloud Development

conclusion

preface

Thanks to the idea provided by OnceLove, with the help of the UI style of his small program, I re-used MPvue to achieve my own wedding invitation, which took 3 days. I had never thought of realizing such a project by myself before, because the backstage part was a troublesome one. So when my daughter-in-law asked me to realize this invitation by myself, I refused at first. Since the Chinese New Year is coming, there is no major update of the company’s project. Taking advantage of this free time, I studied the cloud development of the small program. Without background support, the front and back ends can be realized by themselves.

This small program for the wedding formal use of small program (due to some partners of uncivilized behavior, so can only change a small program for everyone to experience), the wedding is coming, interested can scan code experience this project, happy, welcome to experience, have any questions can give me a message in this article

Welcome to experience:



Source address: https://gitee.com/roberthuang123/wedding

The preparatory work

  1. Mpvue Framework MpVue official document
  2. Applets · Cloud Development Applets · Cloud development documentation

Note: Before using MPVue, you should first familiarize yourself with the basics of the Vue framework

Project Structure Introduction

Common directory: Put some common resources, such as JS, CSS, JSON

Components directory: this is where the component-related. Vue files are stored

Pages directory: All pages are in this directory

Utils directory: generated automatically when using mpvue and can be ignored

App. Json file:

{
  "pages": [
    "pages/index/main"."pages/photo/main"."pages/map/main"."pages/greet/main"."pages/message/main"]."window": {
    "backgroundTextStyle": "light"."navigationBarBackgroundColor": "#fff"."navigationBarTitleText": "WeChat"."navigationBarTextStyle": "black"
  },
  "tabBar": {
    "color": "#ccc"."selectedColor": "#ff4c91"."borderStyle": "white"."backgroundColor": "#ffffff"."list": [{"pagePath": "pages/index/main"."iconPath": "static/images/1-1.png"."selectedIconPath": "static/images/1-2.png"."text": "Invitation letter"
      },
      {
          "pagePath": "pages/photo/main"."iconPath": "static/images/2-1.png"."selectedIconPath": "static/images/2-2.png"."text": "Sweet album"
      },
      {
          "pagePath": "pages/map/main"."iconPath": "static/images/3-1.png"."selectedIconPath": "static/images/3-2.png"."text": "Hotel Navigation"
      },
      {
          "pagePath": "pages/greet/main"."iconPath": "static/images/4-1.png"."selectedIconPath": "static/images/4-2.png"."text": "Best friend wishes"
      },
      {
          "pagePath": "pages/message/main"."iconPath": "static/images/5-1.png"."selectedIconPath": "static/images/5-2.png"."text": "Leave a comment"}},"requiredBackgroundModes": ["audio"]}Copy the code

App.vue file: I add some relevant contents in this file mainly to remind you of the update of the project. The contents are as follows:

<script>
export default {
  onLaunch() {// Check whether the applet has a new version updateif (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function(res) {// Request a callback for the new version informationif (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: 'Update Prompt',
              content: 'The new version is ready. Do you want to restart the application? ',
              success: function (res) {
                if(res. Confirm) {/ / download the new version of good, call applyUpdate application. The new version and restart updateManager applyUpdate ()}}})}) / / small program with the new version, Wx.getupdatemanager ().onUpdateFailed()function() {// When the new version fails to download, a callback is performed to wx.showmodal ({title:'tip',
              content: 'New version found, download failed, please check network Settings',
              showCancel: false})})}})}elseWx. showModal({title:'tip',
        confirmColor: '#5BB53C',
        content: 'The current wechat version is too early to use this function. Please upgrade to the latest wechat version and try again. '
      })
    }
  }
}
</script>

<style lang="stylus">
page
    height 100%
image
    display block
</style>
Copy the code

The main. Js file:

import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false
App.mpType = 'app'

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

const app = new Vue(App)
app.$mount(a)Copy the code

Functions: this directory contains cloud functions, which will be discussed later in this article

Images directory: Mainly contains static resource images

The page is introduced

  • Home page — Invitation letter

The home page focuses on the realization of background music with you

const audioCtx = wx.createInnerAudioContext()

First of all, wx. CreateInnerAudioContext interface for instance

Then, through the relevant method of the example to realize the function of music playback and pause

Applets audio related documentation

The specific code is as follows:

<script>
import IndexSwiper from 'components/indexSwiper'
import tools from 'common/js/h_tools'
const audioCtx = wx.createInnerAudioContext()
export default {
  name: 'Index',
  components: {
    IndexSwiper
  },
  data () {
    return {
      isPlay: true,
      list: []
    }
  },
  onShow () {
    const that = this
    that.isPlay = true
    that.getMusicUrl()
  },

  methods: {
    audioPlay () {
      const that = this
      if (that.isPlay) {
        audioCtx.pause()
        that.isPlay = false
        tools.showToast('You have paused music ~')}else {
        audioCtx.play()
        that.isPlay = true
        tools.showToast('Background music is on ~')}},getList () {
      const that = this
      const db = wx.cloud.database()
      const banner = db.collection('banner')
      banner.get().then(res => {
        that.list = res.data[0].bannerList
      })
    },

    getMusicUrl () {
      const that = this
      const db = wx.cloud.database()
      const music = db.collection('music')
      music.get().then(res => {
        let musicUrl = res.data[0].musicUrl
        audioCtx.src = musicUrl
        audioCtx.loop = true
        audioCtx.play()
        that.getList()
      })
    }
  },

  onShareAppMessage: function (res) {
    return {
      path: '/pages/index/main'
    }
  }
}
</script>Copy the code

The above code uses the cloud development related functions, the article will be introduced later, please calm down

  • Phase album page – just a round – cast chart, here is not more
  • Map page – here we focus on the map label Map

The map tag documents the use of the Map component

So let’s talk about markers

data () {
    return {
      // qqSdk: ' ',
      markers: [{
        iconPath: '.. /.. /static/images/nav.png'Id: 0, latitude: 30.08059, longitude: 115.93027, width: 50, height: 50}]}Copy the code

<template>
    <div class="map">
        <image mode="aspectFit" class="head-img" src=".. /.. /static/images/t1.png"/>
        <map class="content" id="map" longitude="115.93027" latitude="30.08059" :markers="markers" scale="18" @tap="toNav">
        </map>
        <div class="call">
            <div class="left" @tap="linkHe">
                <image src=".. /.. /static/images/he.png"/> <span> call groom </span> </div> <div class="right" @tap="linkShe">
                <image src=".. /.. /static/images/she.png"/> <span> Call bride </span> </div> <image class="footer" src=".. /.. /static/images/grren-flower-line.png"/>
    </div>
</template>Copy the code

  • Blessing page – also related to cloud development, covered later
  • Comment page – also related to cloud development, covered later

Introduction to Cloud Development

Applets cloud development documentation

  • Project. Config. Json file:
"cloudfunctionRoot": "static/functions/"Copy the code

For cloud development, first we need to find the above file and add the above sentence to the above JSON file

CloudfunctionRoot Is used to specify the directory for storing cloud functions

  • App. Json file:
"window": {
    "backgroundTextStyle": "light"."navigationBarBackgroundColor": "#fff"."navigationBarTitleText": "WeChat"."navigationBarTextStyle": "black"
},
"cloud": trueCopy the code

Added field “cloud”: true for cloud development capability compatibility

  • Cloud development

On the left side of the developer toolbar, click the “Cloud Development” button to open cloud development

  • Cloud development console

  • The database

Cloud development provides a JSON database

  • storage

Cloud development provides storage space and cloud download capability for uploading files to the cloud with permission management. Developers can use the cloud storage function through apis on the small program side and cloud function side.

  • Cloud function

A cloud function is a piece of code that runs in the cloud and can be written in a development tool, uploaded and deployed with one click, without the need to manage a server.

Let’s start with the process of using the cloud:

  1. To initialize the cloud capability, you need to invoke it before the applet starts to use the cloud capabilitywx.cloud.initMethod completes the initialization of cloud capabilities
import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false
App.mpType = 'app'

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

const app = new Vue(App)
app.$mount(a)Copy the code

2. Use of database:

You need to get a reference to the database before you can use the database API for add, delete, change, and query operations. The following call gets a reference to the database for the default environment:

const db = wx.cloud.database()Copy the code

To manipulate a collection, get a reference to it:

const todos = db.collection('todos')Copy the code

Here is an example of working with a database:

Example: The home page to obtain background music resources

getMusicUrl () {
      const that = this
      const db = wx.cloud.database()
      const music = db.collection('music')
      music.get().then(res => {
        let musicUrl = res.data[0].musicUrl
        audioCtx.src = musicUrl
        audioCtx.loop = true
        audioCtx.play()
        that.getList()
      })
}Copy the code

Example: the home page gets the array of multicast graphs

getList () {
      const that = this
      const db = wx.cloud.database()
      const banner = db.collection('banner')
      banner.get().then(res => {
        that.list = res.data[0].bannerList
      })
}Copy the code

For example, on the blessing page, users send blessings to storage users

<script>
import tools from 'common/js/h_tools'
export default {
  name: 'Greet'.data () {
    return {
      userList: [],
      openId: ' ',
      userInfo: ' '}},onShow () {
    const that = this
    that.getUserList()
  },
  methods: {
    scroll (e) {
      console.log(e)
    },

    sendGreet (e) {
      const that = this
      if (e.target.errMsg === 'getUserInfo:ok') {
        wx.getUserInfo({
          success: function (res) {
            that.userInfo = res.userInfo
            that.getOpenId()
          }
        })
      }
    },

    addUser () {
      const that = this
      const db = wx.cloud.database()
      const user = db.collection('user')
      user.add({
        data: {
          user: that.userInfo
        }
      }).then(res => {
        that.getUserList()
      })
    },

    getOpenId () {
      const that = this
      wx.cloud.callFunction({
        name: 'user',
        data: {}
      }).then(res => {
        that.openId = res.result.openid
        that.getIsExist()
      })
    },

    getIsExist () {
      const that = this
      const db = wx.cloud.database()
      const user = db.collection('user')
      user.where({
        _openid: that.openId
      }).get().then(res => {
        if (res.data.length === 0) {
          that.addUser()
        } else {
          tools.showToast('You have already sent your blessing.')}})},getUserList () {
      const that = this
      wx.cloud.callFunction({
        name: 'userList',
        data: {}
      }).then(res => {
        that.userList = res.result.data.reverse()
      })
    }
  }
}
</script>Copy the code

  • To enter the blessing page, first we need to get the list of friends who send blessings
getUserList () {
      const that = this
      wx.cloud.callFunction({
        name: 'userList',
        data: {}
      }).then(res => {
        that.userList = res.result.data.reverse()
      })
}Copy the code

The cloud function is used here. The cloud function is used because the server defaults to 20 records at a time when the applets fetch the collection data, while the cloud function returns 100.

Here’s how to use the cloud function:

Json file to configure the location of cloud functions

Here is the index.js file of the cloud function messageList:

const cloud = require('wx-server-sdk') cloud.init() const db = cloud.database() const MAX_LIMIT = 100 exports.main = async (event, Const countResult = await db.collection(context) const countResult = await db.collection('message').count() const total = countresult. total // How many times to count const batchTimes = math.ceil (total / 100) // The array that holds all read promises const tasks = []for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection('message').skip(I * MAX_LIMIT).limit(MAX_LIMIT).get() tasks.push(promise)return (await Promise.all(tasks)).reduce((acc, cur) => ({
    data: acc.data.concat(cur.data),
    errMsg: acc.errMsg
  }))
}
Copy the code

Before using the cloud function, go to the Developer tools and right-click the messageList directory as shown in the following figure:

Click Upload and Deploy: Cloud install dependencies (no upload node_modules)

Get the following prompt:

After installation, click “Finish” to use the current cloud function. Use method:

getUserList () {
      const that = this
      wx.cloud.callFunction({
        name: 'userList',
        data: {}
      }).then(res => {
        that.userList = res.result.data.reverse()
      })
}Copy the code

The array is in reverse order because the newly blessed user is expected to appear first

  • The next step is to store users when they send their blessings

Here we use cloud functions to get user information,

When the small program side calls the cloud function, the openID of the user on the small program side will be injected into the input parameters of the cloud function. The developer does not need to verify the correctness of OpenID, because wechat has completed this part of authentication, and the developer can directly use the OpenID

Here is the index.js file for the cloud function user:

// cloud function entry file const cloud = require('wx-server-sdk'Cloud.init () // exports.main = async (event, context) => {const wxContext = cloud.getwxContext ()return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID
  }
}
Copy the code

To obtain the openID of the current user, obtain the openID of the current user:

getOpenId () {
      const that = this
      wx.cloud.callFunction({
        name: 'user',
        data: {}
      }).then(res => {
        that.openId = res.result.openid
        that.getIsExist()
      })
}Copy the code

The getIsExist() method then determines whether the current user already exists in the database:

getIsExist () {
      const that = this
      const db = wx.cloud.database()
      const user = db.collection('user')
      user.where({
        _openid: that.openId
      }).get().then(res => {
        if (res.data.length === 0) {
          that.addUser()
        } else {
          tools.showToast('You have already sent your blessing.')}}}Copy the code

If the array length is zero, the user is added to the database; otherwise, the current user is reminded of the blessing

Here’s how to store user information, addUser():

addUser () {
      const that = this
      const db = wx.cloud.database()
      const user = db.collection('user')
      user.add({
        data: {
          user: that.userInfo
        }
      }).then(res => {
        that.getUserList()
      })
}Copy the code

The information stored in the database looks like this:

Some people want to see the database field, actually very simple, this is the home page of the rotation map field, see the following figure:

This is the comment on the message, as shown in the picture:



conclusion

Here are a few details:

  1. Cloud development is free;
  2. The database collection name must first be created;
  3. When the database set is empty, I did not deal with details here, will report an error, first through the use of their own small program to write a data, the error can be solved;
  4. After cloud functions are created, make sure to create and install dependencies.
  5. If you are worried that some comments are not friendly and want to have the deletion function, you can open the permission to yourself and add a deletion button to each comment. Only when you use it, you can control the deletion button to be visible through the unique OpenID, so as to manage the message list.
  6. After the database set up, remember to release the permissions, as shown below:



Conclusion:

  1. In addition to some static resources in the project, other resources are recommended to be stored in cloud development-storage management. In this way, it is convenient to replace resources without submitting them again for small program review, and the replaced resources can take effect immediately.
  2. I know that everybody likes be can directly see the same effect, because this project involves the background data, can’t completely put my environment for everyone to use, recommended really function to implement related or similar project friend against my train of thought to do a belong to his own work to the most meaningful.
  3. The general function is so much, I hope to help you, remember to give the author a thumbs up if you feel good, your support is the biggest power I keep updating!

Recent updates

Recently updated some content, not going to open source, you can add wechat (huangbin910419) into the group, students with problems can seek help in the group, into the group remarks: wedding invitation small program

Collection name and corresponding data structure

Since many students asked me to know about collections and data structures, the following pictures are what you want. Other collections are needed for later optimization, and the code of the optimization part is not publicly available, so you don’t need to care about this part of the collection