git項目位址:https://github.com/luoluo5945/wepy-min-program
參考部落格:https://www.jianshu.com/p/ba780cfcc5d5
WePY項目的建立與使用
全局安裝或更新WePY指令行工具
npm install wepy-cli -g
在開發目錄中生成Demo開發項目, 1.7.0之後版本請移步wepy-cli文檔
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
在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()
}
}