欧美三级国产三级日韩三级_亚洲熟妇丰满大屁股熟妇_欧美亚洲成人一区二区三区_国产精品久久久久久模特

微信小程序項目wx-store代碼詳解 - 新聞資訊 - 云南小程序開發(fā)|云南軟件開發(fā)|云南網(wǎng)站建設-昆明葵宇信息科技有限公司

159-8711-8523

云南網(wǎng)建設/小程序開發(fā)/軟件開發(fā)

知識

不管是網(wǎng)站,軟件還是小程序,都要直接或間接能為您產(chǎn)生價值,我們在追求其視覺表現(xiàn)的同時,更側重于功能的便捷,營銷的便利,運營的高效,讓網(wǎng)站成為營銷工具,讓軟件能切實提升企業(yè)內部管理水平和效率。優(yōu)秀的程序為后期升級提供便捷的支持!

您當前位置>首頁 » 新聞資訊 » 小程序相關 >

微信小程序項目wx-store代碼詳解

發(fā)表時間:2021-1-5

發(fā)布人:葵宇科技

瀏覽次數(shù):64

本文會講解一下這個小程序的代碼,所有代碼幾乎是我一個個敲出來的,所有邏輯也是自己構思梳理的,因此很多實現(xiàn)方式并不是很好,冗余代碼很多,代碼質量堪憂,但我也在學習中,隨著技術提升,會不斷來重構代碼,如果大家有任何建議歡迎私信我哦,特別感謝。?

該小程序采用的云開發(fā),沒有自己搭建后端,我心目中,只要沒有后端的內容我就覺得很簡單。但其實我還是想有朝一日能自己獨立完成前后端所有工作,寫一個更棒的作品。


啟動頁

之前文章也有過如何寫一個啟動頁面。至于為什么需要個啟動頁呢?

我覺得主要也就兩點,一個是好看,還有個就是添加獲取用戶信息類型按鈕,間接引導用戶授權獲取用戶信息。

至于為啥要獲取用戶信息?

曾真有段時間,我糾結了好久,因為我自己這個程序中,除了展示,好像也沒啥需要用到這個數(shù)據(jù)的地方。

但我還是寫了。

當前登陸用戶的用戶名和頭像圖片,通過 open-data 標簽可以無需授權直接獲取,只要指定相應類型userNickName和userAvatarUrl即可,樣式只需要用view容器包裹起來進行設置。button按鈕指定open-type為getUserInfo,在點擊事件中就可以拿到授權之后的用戶公開信息數(shù)據(jù)。

拿到用戶信息需要保存到數(shù)據(jù)庫中,也只需要首次登錄的用戶在授權之后才需要入庫,所以加個判斷當前登陸用戶是否是首次登錄,判斷條件是每個用戶的唯一值openId。

通過這個邏輯,那需要處理的可以分為如下幾個:

1、獲取當前登錄用戶的openId。

復制代碼
getOpenID() {
    let that = this;
    wx.cloud.callFunction({
        name: 'login',
        complete: res => {
            const openId = res.result.event.userInfo.openId;
            that.setData({
                openId
            })
        }
    })
},
復制代碼

這個login云函數(shù)是項目構建時自動生成的,云函數(shù)寫法:

復制代碼
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
    env: wxContext.ENV,
  }
}
復制代碼

 2、獲取數(shù)據(jù)庫中所有用戶數(shù)據(jù)。

復制代碼
getUsersList() {
    const that = this;
    db.collection('users').get({
        success: res => {
            that.setData({
                usersList: res.data,
            })
        },
        fail: console.error
    })
},
復制代碼

3、在頁面剛加載的時候調用上面兩個方法,拿到openId和userList。在點擊按鈕時,檢查當前登錄用戶是否已經(jīng)存在數(shù)據(jù)庫。

復制代碼
goToIndex(e) {
    const that = this;
    const auth = e.detail.errMsg;
    wx.switchTab({
        url: '/pages/index/index',
    });
    if(auth === "getUserInfo:ok") {
        const avatarUrl = e.detail.userInfo.avatarUrl;
        const nickName = e.detail.userInfo.nickName;
        that.checkUser(nickName, avatarUrl);
    }
},
復制代碼

這里獲取到用戶信息數(shù)據(jù)是這個樣子滴:

?

4、檢查當前登錄用戶是否已經(jīng)存在數(shù)據(jù)庫。

復制代碼
checkUser(name, url) {
    const that = this;
    const list = this.data.usersList;
    const openId = this.data.openId
    const ids = [];
    list.forEach((item) => {
        ids.push(item._openid);
    })
    if(ids.indexOf(openId) === -1) {
        that.setUserInfo(name, url)
    } else {
        return;
    }
},
復制代碼

5、如果不存在的話,將該用戶信息存入數(shù)據(jù)庫users中。管它有用沒用,先存著唄。

復制代碼
setUserInfo(name, url) {
    db.collection('users').add({
        data: {
            nickName: name,
            avatarUrl: url,
        }
    })
},
復制代碼

數(shù)據(jù)庫中會自動給這個字段生成一個id和openId。

?

首頁

首頁從上到下分為幾塊,輪播圖,輪播告示,icon列表,推薦商品展示。

輪播圖。

直接用自帶的組件,swiper和swiper-item配合使用。

<swiper class="swiper-top" indicator-dots="true" indicator-active-color="#fff" autoplay circular>
  <swiper-item wx:for="{{bannersList}}" wx:key="item">
    <image mode="aspectFill" data-url="{{item}}" src="{{item}}" />
  </swiper-item>
</swiper>

圖片數(shù)據(jù)來自數(shù)據(jù)中定義好的。

復制代碼
getBannerList() {
  db.collection('banners').get({
    success: res=> {
      this.setData({
        bannersList: res.data[0].imgs,
      })
    },
    fail: console.error
  })
}
復制代碼

因為之前有小伙伴咨詢過,如何云開發(fā)中數(shù)據(jù)庫新建集合,這里用gif簡單說明一下。

?

為啥要兩個gif呢,因為超過300幀的它不給上傳~

輪播告示。

和輪播圖一樣的,只是輪播方向不同,swiper中添加個參數(shù) vertical。點擊顯示彈窗,引用的是WeUI庫,咋用參考以往文章。

icon列表。

到這里就要用到本程序中最最最復雜的一個數(shù)據(jù)庫集合了,幾乎所有的商品數(shù)據(jù)都是存放在這個集合中的。

?

那icon列表就是獲取goods集合中每個對象icon字段值,推薦商品列表就是每個對象中l(wèi)ist數(shù)組中所有isHot為true的數(shù)據(jù)。

復制代碼
getIconList() {
  const that = this;
  const arr = [];
  db.collection('goods').get({
    success: res=> {
      const list = res.data;
      list.forEach((item) => {
        item.list.forEach((d) => {
          if(d.isHot) {
            const param = {
              ...d,
              categoryId: item._id
            };
            arr.push(param);
          }
        })
      })
      that.setData({
        categories: list,
        goodsRecommend: arr
      })
    },
    fail: console.error
  })
},
復制代碼

給每個icon圖片上加一個跳轉到分類頁的點擊事件,一般的跳轉可以使用wx.navigateTo,而tab頁的跳轉只允許使用wx.switchTab,官方文檔中指明這個方法是不可以后綴參數(shù)的。

而我這里肯定是需要點擊不同的icon跳轉到不同的分類欄目中的,那就需要在跳轉時候攜帶該分類id,還是當前這個數(shù)組的下標。

通過定義全局參數(shù),可以解決wx.switchTab無法攜帶參數(shù)的問題。

app.js中,在onLaunch里定義個全局對象。

this.globalData =http://www.wxapp-union.com/ {
  categoryParamId: 0,
  categoryParamIndex: 0,
}

商品分類頁

在menu.js中,在最開始需要引入全局變量。

const app = getApp()

那上面定義的globalData可以直接通過app拿到。

分類頁這兒主要的處理邏輯有三塊內容。

1、區(qū)分管理員權限和普通用戶權限。

管理員權限可以有新增商品和刪除的功能,普通用戶只可以查看。

權限這塊的處理應該會有更好的方案。

我比較挫,想到的最簡單的方法就是利用openId來做過濾。在頁面初次加載的時候獲取當前用戶的openId,和啟動頁一樣的方法,只是回調函數(shù)中不一樣。在數(shù)據(jù)庫中定義個管理員集合,你需要給那些用戶設置成管理員,將他們的openId放在這個集合中。

我是在app.js中獲取這個管理員集合的,可能是剛剛嘗過全局變量的甜頭吧。

wx.cloud.database().collection('adminList').get({
    success: res => {
      this.adminList = res.data[0].admin_openId;
    },
})

那在menu.js中可以直接拿到這個adminList中數(shù)據(jù),判斷一下當前登錄用戶的openId在不在adminList中。

復制代碼
getOpenID() {
  let that = this;
  wx.cloud.callFunction({
    name: 'login',
    complete: res => {
      const openId = res.result.event.userInfo.openId;
      if(app.adminList.indexOf(openId) === -1) {
        that.setData({
          isAdmin: false
        })
      } else {
        that.setData({
          isAdmin: true
        })
      }
    }
  })
},
復制代碼

2、將設置成喜歡狀態(tài)的商品數(shù)據(jù)存入本地緩存。

當時對于這個邏輯處理的考慮也是想了蠻久,這個小程序的制作出發(fā)點只是作為一個助手作用,方便用戶查看店鋪所有商品,是做一個商品分類展示的功能,不支付線上下單,主要也是因為顯示下單這個功能太復雜,個人小程序沒權限做。

那我就想著僅僅分類展示并不滿足使用,加入個喜歡列表實用性更大。

商品的固定數(shù)據(jù)是可以存入云開發(fā)的數(shù)據(jù)庫中,但是針對于每個用戶不同的喜歡數(shù)據(jù),最好的方案就是使用緩存。

localStorange的數(shù)據(jù)形式是key / value,一開始計劃的是固定一個key,value中是個數(shù)組對象。    

這一定是可行的,但我不會做......麻煩能實現(xiàn)的朋友私信我。

好的方案來不了可以來挫的嘛。我用商品的分類Id和當前商品Id拼接起來作為key,這就保證了key唯一性,那存入本地的數(shù)據(jù)是需要在喜歡列表展示的,我需要展示的數(shù)據(jù)有分類Id,id,商品名,是不是喜歡,封面縮略圖,價格。明白了這幾點要求,實現(xiàn)就很簡單了。

在每個商品的愛心圖標上加一個點擊事件。

復制代碼
joinFavorites(e) {
  const that = this;
  const id = e.currentTarget.dataset.id;
  const index = e.currentTarget.dataset.index;
  const list = this.data.goodsList[this.data.curIndex].list;
  const loveList = [];
  list.forEach((item) => {
    if (item.id === id) {
      item.isLove = !item.isLove;
    }
    const param = {
      categoryId: this.data.curNav,
      id: item.id,
      name: item.goodsName,
      isLove: item.isLove,
      thumbnail: item.imgs[0],
      price: item.newPrice
    };
    loveList.push(param);
  })
  that.setData({
    goodsList: this.data.goodsList,
  })

  // 緩存的key以分類id和服裝id用-連接
  const key = loveList[index].categoryId + "-" + loveList[index].id;
  this.saveLocally(key, loveList[index]);
},
// 存入本地緩存
saveLocally(key, data) {
  wx.setStorage({
    key,
    data,
  })
},
復制代碼

現(xiàn)在看這個代碼,我覺得還是可以再重構優(yōu)化的更好的。

3、從本地緩存中獲取喜歡列表詳情

有些商品是已經(jīng)加入喜歡列表的,商品上的喜歡圖標已經(jīng)是高亮狀態(tài),等到下次進入該分類頁,就應該將之前設置喜歡狀態(tài)的商品顯示出來,不然每次進來都是初始的模樣就毫無意義了。

首先是需要獲取商品列表數(shù)據(jù),再根據(jù)本地緩存數(shù)據(jù),將喜歡的商品數(shù)據(jù)修改一下狀態(tài)。

這樣就是分三步走。

獲取商品列表數(shù)據(jù)。

復制代碼
getGoodsList() {
  const that = this;
  db.collection('goods').get({
    success: res => {
      const list = res.data;
      that.getDetails(that.data.storageData, list);

      that.setData({
        goodsList: list,
      })
    }
  })
},
復制代碼

讀取緩存數(shù)據(jù)。

復制代碼
getLocally() {
  const that = this;
  wx.getStorageInfo({
    success(res) {
      if (res.currentSize > res.limitSize) {
        that.setData({
          isDialog: true
        })
      } else {
        that.setData({
          storageData: res.keys
        })
      }

    },
  })
},
復制代碼

從本地緩存中獲取喜歡列表詳情。

復制代碼
getDetails(localArr, goodsList) {
  const that = this;
  localArr.forEach((localItem) => {
    const itemPId = localItem.split("-")[0].toString();
    const itemId = localItem.split("-")[1].toString();
    goodsList.forEach((goodItem) => {
      if (itemPId === goodItem._id) {
        goodItem.list.forEach((item) => {
          if (itemId === item.id.toString()) {
            wx.getStorage({
              key: localItem,
              success(res) {
                item.isLove = res.data.isLove
                that.setData({
                  goodsList,
                })
              }
            })
          }
        })
      }
    })
  })
},
復制代碼

主要的處理邏輯就是以上這三塊。還有些其他的交互方法,商品分類的切換,詳情頁跳轉,商品刪除......這些就不寫了,可以去看代碼,都很容易理解的。

商品詳情頁

點擊跳轉過來的時候,攜帶的參數(shù)只有分類id和商品id。根據(jù)這兩個字段就可以在商品列表數(shù)據(jù)查詢到具體所有數(shù)據(jù)。

在當前頁面獲取傳參過來的數(shù)據(jù)。

onLoad: function (options) {
    this.setData({
        categoryId: options.categoryId,
        id: options.id
    });
}

新增商品頁

按照之前數(shù)據(jù)庫集合中定義的數(shù)據(jù)格式,這里就分兩塊。一個是相關數(shù)據(jù)的填寫表單,一個就是上傳的圖片列表。

圖片列表上傳的實現(xiàn),官方都給了相應的api方法。

選擇圖片:

復制代碼
wx.chooseImage({
    sizeType: ["original", "compressed"], // 可以指定是原圖還是壓縮圖,默認二者都有
    sourceType: ["album", "camera"], // 可以指定來源是相冊還是相機,默認二者都有
    success: function (res) {
        // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標簽的src屬性顯示圖片
        var tempFilePaths = res.tempFilePaths;
        var imgs = that.data.imgs;
        for (var i = 0; i < tempFilePaths.length; i++) {
            if (imgs.length >= 9) {
                that.setData({
                    imgs: imgs,
                });
                return false;
            } else {
                const filePath = res.tempFilePaths[i];
                var timestamp = Date.parse(new Date());
                const cloudPath = `${timestamp}-${i}`;
                const param = {
                    cloudPath,
                    filePath,
                };
                imgs.push(param);
            }
        }
        that.setData({
            imgs: imgs,
        });
    },
});
復制代碼

上傳圖片:

復制代碼
uploadImgs(list) {
    const that = this;
    const imgList = [];
    list.forEach((item) => {
        wx.cloud.uploadFile({
            cloudPath: `uploadImgs/${item.cloudPath}`, // 存入uploadImgs文件夾中
            filePath: item.filePath, // 文件路徑
        }).then((res) => {
            if(res.errMsg === "cloud.uploadFile:ok") {
                imgList.push(res.fileID)
            }
            that.setData({
                imgList,
            })
            if(that.data.imgList.length === that.data.imgs.length) {
                that.add()
            }
        })
        .catch((error) => {
            console.log(error);
        });
    });
},
復制代碼

最終把表單數(shù)據(jù)和圖片列表數(shù)據(jù)到存入數(shù)據(jù)庫集合中。

復制代碼
add() {
    const that = this;
    wx.cloud.callFunction({
        name: 'addGoods',
        data: {
            categoryId: that.data.categoryId,
            id: that.data.id,
            goodsName: that.data.goodsName,
            newPrice: that.data.newPrice,
            oldPrice: that.data.oldPrice,
            isHot: that.data.isHot,
            imgs: that.data.imgList
        }
        }).then()
},
復制代碼

商品新增的云函數(shù):

復制代碼
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
exports.main = async (event, context) => {
    const goodsName = event.goodsName;
    const categoryId = event.categoryId;
    const id = event.id;
    const newPrice = event.newPrice;
    const oldPrice = event.oldPrice;
    const isHot = event.isHot;
    const imgs = event.imgs;
    db.collection("goods").doc(categoryId).update({
        data: {
            list: _.push({
                id,
                goodsName,
                newPrice,
                oldPrice,
                isHot,
                imgs
            })
        }
    })

    return {
        categoryId,
        id,
        goodsName,
        newPrice,
        oldPrice,
        isHot,
        imgs
    }
}
復制代碼

喜歡列表頁

最輕松的一個頁面,讀取本地緩存展示數(shù)據(jù)。這里還用到了WeUI的mp-slideview組件,修改這個組件的樣式還是挺麻煩,高度樣式?jīng)]改成功,多少存在點瑕疵。


相關案例查看更多