How to create a small program cloud development project

First, go to apply for an account: https://developers.weixin.qq.com/miniprogram/dev/index.html?t=18090519
Apply for a good account and you will have an appId. If you don’t have an appId, you can’t use Mini Program Cloud developing;

Then, go to download the WeChat developer tools: https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html?t=18092022

Create a new project, choose cloud development as the template;

Insert picture description here
Then, the approximate project directory is only the default directory, including database guidance, uploading pictures and cloud function guidance; do not delete these directories first, they will be useful later, you can refer to them;

Then add a new column, the tabBar in app.json changes:

,
  "tabBar": {
    "color": "#666666",
    "selectedColor": "#580000",
    "borderStyle": "1px solid #f5f5f5",
    "backgroundColor": "#fff",
    "list": [
      {
        "pagePath": "pages/index/index",
        "text": "首页",
        "iconPath": "./images/index.png",
        "selectedIconPath": "./images/index1.png"
      },
      {
        "pagePath": "pages/pulish/pulish",
        "text": "发表",
        "iconPath": "./images/pulish.png",
        "selectedIconPath": "./images/pulish1.png"
      },
      {
        "pagePath": "pages/me/me",
        "text": "我的",
        "iconPath": "./images/me.png",
        "selectedIconPath": "./images/me1.png"
      }
    ]
  }

Change pages as follows:

 "pages": [
    "pages/index/index",
    "pages/advice/advice",
    "pages/comment/comment",
    "pages/me/me",
    "pages/upload/upload",
    "pages/itemDetail/itemDetail",
    "pages/pulish/pulish"
   
  
  ],

Save, you will find that the development tool automatically created all non-existent directories in pages for you;

Then, rewrite my page: the
layout is as follows:

<!--pages/me/me.wxml-->
<view class='flexDownC font'>
  <view class='bg flexDownC'>
    <label>
      <image class='userTx' src='{
   
   {userTx || defaultUrl}}'></image>
      <button open-type='getUserInfo' bindgetuserinfo='getUserInfoHandler'></button>
    </label>
    <view>
      <text class='{
   
   { username == "点击头像登录" ? "usernameDe":"username"}} '>{
   
   {username}}</text>
    </view>
  </view>

  <view class='flexDownC mt80 rows'>
    <navigator url='../comment/comment' class='row'>
    <view class=" navRow flexSpaceBet">
      <text>我的评论</text> 
      <image src='../../images/left.png' class='navTo'></image>
    </view>
     </navigator>
    <navigator url='../upload/upload' class='row'>
    <view class=" navRow flexSpaceBet">
      <text>我的发布 </text> 
       <image src='../../images/left.png' class='navTo'></image>
    </view>
    </navigator>
    <navigator url='../advice/advice'  class='row'>
    <view class=" navRow flexSpaceBet">
      <text> 建议反馈 </text> 
       <image src='../../images/left.png' class='navTo'></image>
    </view>
    </navigator>
    <view class="row navRow flexSpaceBet " bindtap='showInfo'>
      <text class='pl10'> 关于 </text> 
       <image src='../../images/left.png' class='navTo'></image>
    </view>
  </view>
</view>

It can be found that we first set the login text to "click avatar login" by default, and then once the user logs in, it can be replaced immediately. I changed the user's avatar, name, and userId to the local, using wx.setStorageSync( ) Save, where userId uses a unique generated id created by myself (now there is a problem that has not been solved, that is, once the user's information expires, a userId will be generated again, I think this later change to use WeChat's openId will be better);

When logging in, we randomly generate an id and save it (but the most important thing is to use WeChat's openid, which is the only one that is not repeated and unchanged). When obtaining the openid, set it to save the
login locally . code show as below:

,

  getUserInfoHandler: function(e){
   
    console.log(e)
    let d = e.detail.userInfo
    this.setData({
      userTx: d.avatarUrl,
      username: d.nickName
    })
    wx.setStorageSync('username', d.nickName)
    wx.setStorageSync('avatar', d.avatarUrl)

    const db = wx.cloud.database()
    const _ = db.command
    var userId = wx.getStorageSync('userId')
    if (!userId) {
      userId = this.getUserId()
    }

    db.collection('users').where({
      _openid: d.openid
    }).get({
      success: res=>{
        console.log('查询用户:',res)
        if (res.data && res.data.length > 0){
          console.log('已存在')
          wx.setStorageSync('openId', res.data[0]._openid)
        }else{

          setTimeout(() => {
            db.collection('users').add({
              data: {
                userId: userId,
                iv: d.iv
              },
              success: function () {
                wx.showToast({
                  title: '用户登录成功',
                })
                console.log('用户id新增成功')
                db.collection('users').where({
                  userId: userId
                }).get({
                  success: res => {
                    wx.setStorageSync('openId', res.data[0]._openid)
                  },
                  fail: err=>{
                    console.log('用户_openid设置失败')
                  }
                })
              },
              fail: function (e) {
                console.log('用户id新增失败')
              }
            })
          }, 100)
        }
      },
      fail: err=>{

      }
    })

    
  },

Generate a unique id, using a letter or number + 1970 to the present millisecond + a random number of 10w, the code is as follows:

  getUserId: function () {
    var w = "abcdefghijklmnopqrstuvwxyz0123456789",
      firstW = w[parseInt(Math.random() * (w.length))];

    var userId = firstW + (Date.now()) + (Math.random() * 100000).toFixed(0)
    console.log(userId)
    wx.setStorageSync("userId", userId)

    return userId;
  },

Then, there is a showInfo method: (disclaimer regarding copyright)

 showInfo: function(){
    wx.showModal({
      title: '关于糗皮虎',
      content: '本小程序的内容来源于网上各大平台(如糗百等),如有侵权,请联系管理员***@gmail.com',
      showCancel: false
    })
  }

Finally, in the onLoad method, add the following code:

   let username = wx.getStorageSync('username'),
      avatar = wx.getStorageSync('avatar');
    if (username){
      this.setData({
        username: username,
        defaultUrl: avatar
      })
    }

In the data array above the onload method, add the following fields:

  data: {
    userTx: '',
    defaultUrl: '../../images/tx.png',
    username: '点击头像登录',
    userTx: ''

  },

So, so far, my page function is basically completed
,: please see the detailed code

Guess you like

Origin blog.csdn.net/diaojw090/article/details/93708711