微信小程序框架Wepy筆記

使用wepy前

請先過一遍小程序官方文檔:https://developers.weixin.qq.com/miniprogram/dev/index.html?t=19040122

當然要先會一些vue,以及redux的基礎:

vue官方文檔:https://cn.vuejs.org/v2/guide/

redux中文文檔:https://www.redux.org.cn/

其次wepy安裝請自行查看文檔:https://tencent.github.io/wepy/document.html#/./doc.cli

接着請學習(大佬請跳過,以下爲個人認爲比較好的教程~)

1.promise:

參考資料:

ES6 Promise 用法講解

視頻教學:

【ES6-Promise】新的異步解決方案 脫離回調噩夢

2.async,await:

參考資料:

理解 JavaScript 的 async/await

視頻教學:

async & await 【陳瀟冰】

【ES7】async - await 可能是目前異步最好的解決方案吧

注意:wepy項目中使用Promise

        npm install wepy-async-function --save

        import 'wepy-async-function';  

  • 進入項目根目錄,安裝polyfill
  • 在app.wpy中引入polyfill
  • 在app.wpy中使API promise化
export default class extends wepy.app {

    constructor () {
        super();
        this.use('promisify');
    }

}

我目前的項目處理異步請求是這樣的。

async onLoad() {
    let show = await wepy.login();
    if (show.errMsg == 'login:ok') {
      this.code = show.code;
      this.$apply();
    }
  }

在wepy中去除了setData這個方法,其次this.$apply()是一種髒檢查,異步更新數據,手動刷新dom的時候必須使用。

關於頁面API的封裝

新建一個wxRequest.js

//wxRequest.js
import wepy from 'wepy'

const wxReq = async(parmas, url) => {
    let res = await wepy.request({
      url: url, //開發者服務器接口地址",
      data: parmas.query, //請求的參數",
      method: parmas.method || 'GET',
      header: { 'Content-Type': 'application/json' }
    });

    return res
}

module.exports = {
    wxReq
}

封裝所有的請求 api.js

//api.js
import { wxReq } from '@utils/wxReq';

const baseUrl = '';

const getUserInfo = (pramas) => wxReq(pramas, baseUrl+ 'v2/getrUserInfo');

export default {
    getUserInfo
}

 在pages中使用:

import api from '@somepath/api'

async getUserInfo(){
    let res = await api.getUserInfo({
        query: {
            code: '123',
            id: 12
        },
        method: 'POST'
        })
    })

} 

語法注意

雖說wepy語法接近vue.js,但是還是有一些差異的,下面稍微提一下我使用的時候踩到的坑~

template

        <view class="show-box contorl-detail" wx:if="{{ hasLength }}">
            <view class="head-img-box">
                <repeat for="{{array}}" key="index" index="index" item="item">
                    <view class="head-img">
                       <image  src="{{ imgLeftSrc }}" mode="scaleToFill" lazy-load="false">
                        </image>
                        <view class="arrow"></view>
                        <view class="left-content">{{ item.leftText }}</view>
                    </view>
                </repeat>
            </view>
        </view>

script

data = {
    hasLength: false,
    code: null,
    leftText: '',
    imgLeftSrc: '',
    model: '聊天暱稱',
    leftOrRight: 'left',
    array: [],
    items: [
      { name: 'left', value: '左邊聊天' },
      { name: 'right', value: '右方聊天' }
    ]
  }

template中 :wx:if="{{ hasLength }}" 請注意=號後的屬性值調用的是data中的數據,必須加上雙花括號,這一點更像原生小程序的語法。

相比於wx:for而言,使用repeat標籤我認爲更好一些,把需要循環的所有內容直接放在repeat中,可以避免wx:if和wx:for的衝突,

當然在vue中套一層template,也沒多大影響~

在wepy中,假設你要遍歷的是子組件,那麼此時就必須使用repeat。

官方栗子:

/**
project
└── src
    ├── components
    |   └── child.wpy
    ├── pages
    |   ├── index.wpy    index 頁面配置、結構、樣式、邏輯
    |   └── log.wpy      log 頁面配置、結構、樣式、邏輯
    └──app.wpy           小程序配置項(全局樣式配置、聲明鉤子等)
**/

// index.wpy

<template>
    <!-- 注意,使用for屬性,而不是使用wx:for屬性 -->
    <repeat for="{{list}}" key="index" index="index" item="item">
        <!-- 插入<script>腳本部分所聲明的child組件,同時傳入item -->
        <child :item="item"></child>
    </repeat>
</template>

<script>
    import wepy from 'wepy';
    // 引入child組件文件
    import Child from '../components/child';

    export default class Index extends wepy.page {
        components = {
            // 聲明頁面中要使用到的Child組件的ID爲child
            child: Child
        }

        data = {
            list: [{id: 1, title: 'title1'}, {id: 2, title: 'title2'}]
        }
    }
</script>

script中,在vue中,方法是全部寫在methods中..

注意,對於WePY中的methods屬性,因爲與Vue中的使用習慣不一致,非常容易造成誤解,這裏需要特別強調一下:WePY中的methods屬性只能聲明頁面wxml標籤的bind、catch事件,不能聲明自定義方法,這與Vue中的用法是不一致的。 一般的方法是這樣的

    methods = {
      MethodsOne() {

      },
      MethodsTwo() {

      },
      MethodsThree() {

      },
    }

如果按照上方的配置,對於異步的方法可以考慮和自定義方法一起直接寫在導出的對象中,和methods可以同級

例如:

    async MethodsOne() {
      let res = await function ajax(){}
    }

    async MethodsTwo() {
      let res = await function fetch(){}
    }

    async MethodsThree() {
      let res = await function request(){}
    }
    
    myEvent() {
        console.log('我是自定義事件')
    }

    methods = {
      MethodsOne() {

      },
      MethodsTwo() {

      },
      MethodsThree() {

      },
    }

時間不是很多,我也比較懶,所以暫時寫到這裏,以上有任何錯誤,歡迎留言指出~ 

貼一張前端微信的交流羣,羣內有超級大佬噢~


失效了請加我wx:JJvae1 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章