### Install Westore Core Library Source: https://github.com/tencent/westore/blob/master/README.md This snippet provides the command to install the Westore core library using npm, along with a reference to the official WeChat Mini Program documentation for npm support. ```bash npm i westore --save ``` -------------------------------- ### Install Westore via npm Source: https://github.com/tencent/westore/blob/master/assets/set-data.md Provides the command to install the `westore` library as a development dependency in a WeChat Mini Program project using npm. This is the first step to integrate Westore into your project. ```bash npm i westore --save ``` -------------------------------- ### Example Westore HomeStore Implementation for Mini Programs Source: https://github.com/tencent/westore/blob/master/README.md This JavaScript example demonstrates a `HomeStore` class, which acts as the ViewModel in the Westore architecture. It shows how to instantiate and consume platform-agnostic `Model` instances (`Counter`, `User`), manage the `data` object for the view, and synchronize model changes to the view using the `syncCountModel` and `syncUserModel` methods, which ultimately call `this.update()` to trigger view updates without direct `setData` calls. This illustrates Westore's intuitive programming experience. ```js // 平台无关的 Model import Counter from '../models/counter' // 平台无关的 Model import User from '../models/user' import { Store } from 'westore' // 页面 store,一个页面一个 class HomeStore extends Store { constructor() { super() this.data = { count: 0, motto: 'Hello World', userInfo: null } // 消费 Model this.counter = new Counter() // 消费 Model this.user = new User({ onUserInfoLoaded: () => { this.syncUserModel() } }) this.syncCountModel() } // 同步 Model 的数据到 ViewModel 并更新视图 syncCountModel () { this.data.count = this.counter.count this.update() } // 同步 Model 的数据到 ViewModel 并更新视图 syncUserModel () { this.data.motto = this.user.motto this.data.userInfo = this.user.userInfo this.update() } increment() { this.counter.increment() this.syncCountModel() } decrement() { this.counter.decrement() this.syncCountModel() } getUserProfile() { this.user.getUserProfile() } } module.exports = new HomeStore ``` -------------------------------- ### Westore Integration in WeChat Mini Program Logs Page Source: https://github.com/tencent/westore/blob/master/assets/set-data.md An example of `westore` usage in a `logs.js` page, demonstrating how `update(this)` is applied after data manipulation within the `onLoad` lifecycle hook to update the view. ```js // logs.js const util = require('../../utils/util.js') const { update } = require('westore') Page({ data: { logs: [] }, onLoad() { this.data.logs = (wx.getStorageSync('logs') || []).map(log => { return { date: util.formatTime(new Date(log)), timeStamp: log } }) update(this) } }) ``` -------------------------------- ### Westore diffData Input Example Source: https://github.com/tencent/westore/blob/master/README.md This JavaScript example demonstrates the input format for the `diff` function in Westore, comparing two complex objects to identify changes. It showcases various data types including numbers, strings, booleans, nested objects, and arrays. ```js diff({ a: 1, b: 2, c: "str", d: { e: [2, { a: 4 }, 5] }, f: true, h: [1], g: { a: [1, 2], j: 111 } }, { a: [], b: "aa", c: 3, d: { e: [3, { a: 3 }] }, f: false, h: [1, 2], g: { a: [1, 1, 1], i: "delete" }, k: 'del' }) ``` -------------------------------- ### Westore diffData Output Example Source: https://github.com/tencent/westore/blob/master/README.md This JavaScript snippet illustrates the output format produced by the `diff` function. The result is a flattened object where keys represent paths to changed or new values, and `null` indicates deleted properties, enabling minimal updates. ```js { "a": 1, "b": 2, "c": "str", "d.e[0]": 2, "d.e[1].a": 4, "d.e[2]": 5, "f": true, "h": [1], "g.a": [1, 2], "g.j": 111, "g.i": null, "k": null } ``` -------------------------------- ### Simplified State Update with Westore Source: https://github.com/tencent/westore/blob/master/README.md This JavaScript example demonstrates how Westore simplifies state updates. Instead of using `setData` with full objects, developers can directly modify `this.data` and then call `this.update()` to trigger a minimal patch based on the `diffData` mechanism. ```js this.data.a.b[1].c = 'f' this.update() ``` -------------------------------- ### Westore Integration in WeChat Mini Program Index Page Source: https://github.com/tencent/westore/blob/master/assets/set-data.md A comprehensive example of integrating `westore` into a typical WeChat Mini Program `index.js` page. It showcases how `update(this)` is used after modifying `this.data` in various lifecycle and event handler methods like `onLoad`, `getUserProfile`, and `getUserInfo`, effectively replacing traditional `setData` calls for improved performance and readability. ```js // index.js // 获取应用实例 const app = getApp() const { update } = require('westore') Page({ data: { motto: 'Hello World', userInfo: {}, hasUserInfo: false, canIUse: wx.canIUse('button.open-type.getUserInfo'), canIUseGetUserProfile: false, canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false }, // 事件处理函数 bindViewTap() { wx.navigateTo({ url: '../logs/logs' }) }, onLoad() { if (wx.getUserProfile) { this.data.canIUseGetUserProfile = true update(this) } }, getUserProfile() { // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗 wx.getUserProfile({ desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写 success: (res) => { console.log(res) this.data.userInfo = res.userInfo this.data.hasUserInfo = true update(this) } }) }, getUserInfo(e) { // 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息 console.log(e) this.data.userInfo = e.detail.userInfo this.data.hasUserInfo = true update(this) } }) ``` -------------------------------- ### Basic Westore `update` Method Usage Source: https://github.com/tencent/westore/blob/master/assets/set-data.md Demonstrates how to use `westore`'s `update` method as an alternative to `setData`. It shows direct modification of `this.data` properties followed by a call to `update(this)` to synchronize changes with the view layer, significantly improving the developer experience by making data manipulation more intuitive. ```js const { update } = require('westore') ... ... getUserInfo(e) { this.data.userInfo = e.detail.userInfo this.data.hasUserInfo = true update(this) // 等同于下面代码: // this.setData({ // userInfo: e.detail.userInfo, // hasUserInfo: true // }) } ``` -------------------------------- ### Configure `project.config.json` for npm Build with Westore Source: https://github.com/tencent/westore/blob/master/assets/set-data.md Provides the necessary configuration for `project.config.json` to resolve common npm build errors, especially when using `westore` in a TypeScript template. This ensures the WeChat developer tool can correctly index and build npm dependencies, allowing the project to run successfully. ```json "packNpmManually": true, "packNpmRelationList": [ { "packageJsonPath": "./package.json", "miniprogramNpmDistDir": "./miniprogram/" } ], ``` -------------------------------- ### Westore Direct Data Assignment and Update Source: https://github.com/tencent/westore/blob/master/assets/set-data.md Illustrates the simplified data modification approach with `westore`, where complex nested data properties can be directly assigned. Changes are then efficiently synchronized with the view layer using a single `update(this)` call, eliminating the need for constructing `setData` paths. ```js this.data.a.b[1].c = 'f' update(this) ``` -------------------------------- ### Westore diffData Core Function Implementation Source: https://github.com/tencent/westore/blob/master/README.md This JavaScript code provides the core implementation of the `diffData` function. It initializes a result object, synchronizes keys, and then recursively compares current and previous states to populate the result with only the necessary changes for efficient patching. ```js export function diffData(current, previous) { const result = {} if (!previous) return current syncKeys(current, previous) _diff(current, previous, '', result) return result } ``` -------------------------------- ### WeChat Mini Program `setData` Data Redundancy Avoidance Source: https://github.com/tencent/westore/blob/master/assets/set-data.md Advises on avoiding redundant data when using `setData` in WeChat Mini Programs. Only data that has a direct dependency in the template rendering should be included, as passing unbound variables causes unnecessary performance consumption and framework processing overhead. ```APIDOC setData操作会引起框架处理一些渲染界面相关的工作,一个未绑定的变量意味着与界面渲染无关,传入setData会造成不必要的性能消耗. setData传入的所有数据都在模板渲染中有相关依赖 ``` -------------------------------- ### Westore Usage in WeChat Mini Program Component Source: https://github.com/tencent/westore/blob/master/assets/set-data.md Shows how `westore` can be seamlessly used within a WeChat Mini Program component. The `update(this)` method is called after direct modification of component `data` properties in methods like `plus` and `minus`, providing a consistent and intuitive data management approach across pages and components. ```js const { update } = require('westore') Component({ data: { count: 1 }, methods: { plus() { this.data.count++ update(this) }, minus(){ this.data.count-- update(this) } } }) ``` -------------------------------- ### `Page` and `Component` `setData` Behavior Differences Source: https://github.com/tencent/westore/blob/master/assets/set-data.md Clarifies the distinct behaviors of the `setData` function when used in `Page` versus `Component` contexts within WeChat Mini Programs. For `Page` instances, `setData` is asynchronous for view updates but synchronous for `this.data` modification, whereas for `Component` instances, `setData` is a synchronous operation. ```APIDOC Page 的 setData 函数用于将数据从逻辑层发送到视图层(异步),同时改变对应的 this.data 的值(同步). Component 的 setData 是同步的操作 ``` -------------------------------- ### WeChat Mini Program `setData` Call Frequency Limit Source: https://github.com/tencent/westore/blob/master/assets/set-data.md Documents the recommended call frequency for the `setData` interface in WeChat Mini Programs. Exceeding 20 calls per second can lead to performance degradation, including processing queue blockages and UI stuttering, due to the overhead of inter-thread communication between the logic and render layers. ```APIDOC setData接口的调用涉及逻辑层与渲染层间的线程通信,通信过于频繁可能导致处理队列阻塞,界面渲染不及时而导致卡顿,应避免无用的频繁调用. 每秒调用setData的次数不超过 20 次 ``` -------------------------------- ### Basic `setData` Usage in WeChat Mini Program Source: https://github.com/tencent/westore/blob/master/assets/set-data.md Illustrates a basic usage of `setData` to update an array element in a WeChat Mini Program. This method is frequently used but can lead to performance issues if not handled carefully due to its underlying communication mechanism between the logic and view layers. ```js this.setData({ 'array[0].text':'changed data' }) ``` -------------------------------- ### WeChat Mini Program `setData` Data Size Limit Source: https://github.com/tencent/westore/blob/master/assets/set-data.md Details the data size limitation for `setData` operations in WeChat Mini Programs. Since data is transferred between the logic and render threads, passing data larger than 256KB (after `JSON.stringify`) significantly increases communication time and can impact performance. ```APIDOC 由于小程序运行逻辑线程与渲染线程之上,setData的调用会把数据从逻辑层传到渲染层,数据太大会增加通信时间. setData的数据在JSON.stringify后不超过 256KB ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.