
Westore 架构和 MVP 架构很相似,但是有许多不同。
随着小程序承载的项目越来越复杂,合理的架构可以提升小程序的扩展性和维护性。把逻辑写到 Page/Component 是一种罪恶,当业务逻辑变得复杂的时候 Page/Component 会变得越来越臃肿难以维护,每次需求变更如履薄冰, westore 定义了一套合理的小程序架构适用于任何复杂度的小程序,让项目底座更健壮,易维护可扩展。
npm i westore --save
npm 相关问题参考:小程序官方文档: npm 支持
开发如下图所示的重命名 app

按照传统的小程序开发三部曲:
省略 wxml、wxss,js 如下:
Page({
data: {
nickName: ''
},
async onLoad() {
const nickName = await remoteService.getNickName()
this.setData({
nickName: nickName
})
},
async modifyNickName(newNickName) {
await remoteService.modifyNickName(newNickName)
},
clearInput() {
this.setData({
nickName: ''
})
}
})
需求开发全部结束。

定义 User 实体:
class User {
constructor({ nickName, onNickNameChange }) {
this.nickName = nickName || ''
this.onNickNameChange = onNickNameChange || function() { }
}
checkNickName() {
// 省略 nickName 规则校验
}
modifyNickName(nickName) {
if(this.checkNickName(nickName) && nickName !== this.nickName) {
this.nickName = nickName
this.onNickNameChange(nickName)
}
}
}
module.exports = User
定义 UserStore:
const { Store } = require('westore')
const User = require('../models/user')
class UserStore extends Store {
constructor(options) {
super()
this.options = options
this.data = {
nickName: ''
}
}
init() {
const nickName = await remoteService.getNickName()
this.user = new User({
nickName,
onNickNameChange: (newNickName)=>{
this.data.nickName = newNickName
this.update()
await remoteService.modifyNickName(newNickName)
}
})
}
async saveNickName(newNickName) {
this.user.modifyNickName(newNickName)
},
modifyInputNickName(input) {
this.data.nickName = input
this.update()
}
}
module.exports = new UserStore
页面使用 UserStore:
const userStore = require('../../stores/user-store')
Page({
data: userStore.data,
onLoad() {
/* 绑定 view 到 store
也可以给 view 取名 userStore.bind('userPage', this)
取名之后在 store 里可通过 this.update('userPage') 更新 view
不取名可通过 this.update() 更新 view
*/
userStore.bind(this)
},
saveNickName(newNickName) {
userStore.saveNickName(newNickName)
},
onInputChange(evt) {
userStore.modifyInputNickName(evt.currentTarget.value)
},
clearInput() {
userStore.modifyInputNickName('')
}
})
目录如下:
├─ models // 业务模型实体
│ └─ snake-game
│ ├─ game.js
│ └─ snake.js
│
│ ├─ log.js
│ ├─ todo.js
│ └─ user.js
│
├─ pages // 页面
│ ├─ game
│ ├─ index
│ ├─ logs
│ └─ other.js
│
├─ stores // 页面的数据逻辑,page 和 models 的桥接器
│ ├─ game-store.js
│ ├─ log-store.js
│ ├─ other-store.js
│ └─ user-store.js
│
├─ utils
详细代码点击这里

MIT
$ claude mcp add westore \
-- python -m otcore.mcp_server <graph>