1. 程式人生 > >微信小程式框架wepy筆記

微信小程式框架wepy筆記

WePY專案的建立與使用

全域性安裝或更新WePY命令列工具

npm install wepy-cli -g

在開發目錄中生成Demo開發專案, 1.7.0之後版本請移步wepy-cli文件

wepy new myproject

1.7.0之後的版本使用 wepy init standard myproject 初始化專案,使用 wepy list 檢視專案模板 切換至專案目錄

cd myproject

安裝依賴

npm  install

開啟實時編譯

wepy build --watch

1. 在wepy中使用promise

在app.wpy中:

import 'wepy-async-function'
export default class extends wepy.app { constructor () { this.use('promisify') } }

在actions中request就可以使用promise了:

export const getListData = createAction(TYPE_NAME, (param) => {
  return new Promise((resolve, reject) => {
    wepy.request({
      url: url,
      method: 'POST',
      data:
param, header: { 'content-type': 'application/json' } }).then((res) => { resolve(res) }).catch((error) => { reject(error) }) }) })

2. 在wepy中使用 wx 物件

在根目錄的eslintrc.js中加上globals: { wx: true }

module.exports = {
  ...
  globals: { wx: true },
  ...
}

3. store結構有三部分actions、reducers、types

storeactionsreducerstypes定義非同步請求對變數進行操作或賦值定義函式名和變數名

在types中定義所有非同步或者非非同步的資料,以及函式名 在reducers中定義對非非同步資料的操作,以及對types中變數的賦值 在actions中定義對非同步資料的操作

注:在reducers中需要注意物件的賦值,返回的物件需要是一個全新的物件,這就意味著不能直接改變原物件並返回,而是要建立一個新的物件並返回

4. 使用redux請求資料

在page中引入 connect getStore connect: 用來連線狀態機,獲取裡面的值 getStore: 用來例項化store,之後就可以使用dispatch

// 引入connect getStore
import { connect, getStore } from 'wepy-redux'
// 引入actions中定義的請求
import { getListData } from '../store/actions'

// 建立連線
@connect({
  listData (state) {
    return state.counter.listData
  }
}, {
  getListData
})
// 例項化store
const store = getStore()
export default class Index extends wepy.page {

  //------- 自定義方法 開始 -------
  getListData (hostId) {
    let param = { id: 1 }
    store.dispatch(getListData(param))
  }
  //------- 自定義方法 結束 -------
  
  onLoad () {
  	// 請求列表資料
    this.getListData()
  }
}