### Console Log Example Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md A simple JavaScript snippet demonstrating how to log global data from an application instance to the console. ```javascript console.log(getApp().globalData.count) // 2 ``` -------------------------------- ### Basic wxbuf Integration in app.js Source: https://github.com/laivv/wxbuf/blob/master/readme.md Demonstrates the initial setup for integrating the wxbuf library into the application's main entry point (app.js). It shows how to import the library and structure the App configuration. ```javascript // app.js import wxbuf from 'wxbuf' App({ globalData: {}, onLaunch() { } //... }) ``` -------------------------------- ### Global Listener Setup (wxbuf.watch) Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Allows for global registration of listeners for various application lifecycle events and user interactions. This provides a centralized way to hook into events across the application. ```js // app.js import wxbuf from 'wxbuf'; wxbuf.watch({ onAppLaunch: function (option) { console.log('onAppLaunch', option); }, onAppShow: async function () { console.log('onAppShow'); }, onAppHide: function () { console.log('onAppHide'); }, onPageLoad: function (option) { console.log('onPageLoad:', option); }, onPageShow: function (option) { console.log('onPageShow:', option); }, onPageScroll: function (option) { console.log('onPageScroll:', option); }, onPageReachBottom: function (option) { console.log('onPageReachBottom:', option); }, onPagePullDownRefresh: function (option) { console.log('onPagePullDownRefresh:', option); }, onTap: function (option) { console.log('onTap:', option); }, onLongpress: function (option) { console.log('onLongpress:', option); }, onLongtap: function (option) { console.log('onLongtap:', option); }, onTouchstart: function (option) { console.log('onTouchstart:', option); }, onTouchmove: function (option) { console.log('onTouchmove:', option); }, onTouchend: function (option) { console.log('onTouchend:', option); }, onTouchcancel: function (option) { console.log('onTouchcancel:', option); }, onTouchforcechange: function (option) { console.log('onTouchforcechange:', option); }, onInput: function (option) { console.log('onInput:', option); }, onFocus: function (option) { console.log('onFocus:', option); }, onBlur: function (option) { console.log('onBlur:', option); }, onConfirm: function (option) { console.log('onConfirm:', option); } }); App({ globalData: {}, onLaunch() { // App initialization logic... } // ... other App lifecycle methods }); /* This setup allows you to define handlers for a wide range of events, including: - App lifecycle: onAppLaunch, onAppShow, onAppHide - Page lifecycle: onPageLoad, onPageShow, onPageScroll, onPageReachBottom, onPagePullDownRefresh - User interactions: onTap, onLongpress, onLongtap, touch events, onInput, onFocus, onBlur, onConfirm */ ``` -------------------------------- ### Page Data and Filter Method Examples Source: https://github.com/laivv/wxbuf/blob/master/docs/DOCS.md Illustrates how to define data in a page and implement filter methods like 'formatDate' that can be used with the 'c-text' component. Shows examples with and without filter parameters. ```javascript Page({ data: { timeStamp: 1714123672808 } }) ``` ```javascript Page({ data: { timeStamp: 1714123672808 }, formatDate(value) { return dayjs(value).format('YYYY-MM-DD') } }) ``` ```javascript Page({ data: { timeStamp: 1714123672808 }, formatDate(value, format) { return dayjs(value).format(format) } }) ``` ```javascript Page({ data: { timeStamp: '' }, formatDate(value, format, defaultValue) { return value ? dayjs(value).format(format) : defaultValue } }) ``` -------------------------------- ### Basic c-loading Usage Source: https://github.com/laivv/wxbuf/blob/master/examples/mini-app-demo/components/c-loading/readme.md Demonstrates the fundamental setup of the c-loading component. It automatically triggers the `loadData` callback when the component is initialized and displays a loading indicator. The loading indicator disappears once the `loadData` function completes its execution. ```wxml ``` ```js Page({ async getData() { await fetch('/user/list') } }) ``` -------------------------------- ### Storage Management APIs (Sync) Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Synchronous APIs for managing local storage. Includes getting, setting, removing, and batch setting key-value pairs, as well as clearing the entire storage. ```APIDOC getStorageSync(key: string): any - Synchronously retrieves data from local storage. - Parameters: - key: The key of the data to retrieve. - Returns: The stored data. setStorageSync(key: string, value: any): void - Synchronously sets data in local storage. - Parameters: - key: The key for the data. - value: The data to store. - Returns: void. removeStorageSync(key: string): void - Synchronously removes data from local storage. - Parameters: - key: The key of the data to remove. - Returns: void. batchSetStorageSync(kvList: array): void - Synchronously sets multiple key-value pairs in local storage. - Parameters: - kvList: An array of {key, data} objects. - Returns: void. clearStorageSync(): void - Synchronously clears all data from local storage. - Returns: void. ``` -------------------------------- ### Global Data (Store) Management APIs Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md APIs for accessing and modifying global application data (store). Supports both synchronous and asynchronous operations for getting and setting data. ```APIDOC getStore(key: string): any - Retrieves a value from the global data store. - Parameters: - key: The key of the data to retrieve. - Returns: The value associated with the key, or undefined if not found. setStore(key: string, value: any): void - Sets a value in the global data store. - Parameters: - key: The key for the data. - value: The data to store. - Returns: void. ``` -------------------------------- ### Get Current Page Instance Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Obtains a reference to the instance of the page that currently hosts the component. This allows components to access and interact with the page's methods and data. ```APIDOC ***getPageInstance*** (): `page` 适用于: `component` 说明:获取当前组件所在页面的实例 例子: ```html ``` ```js // pageA.js Page({ getUserId() { return '1' } }) ``` ```json /** pageA.json **/ { "usingComponents": { "comA": "./comA/index" } } ``` ```js // ./comA/index.js Component({ methods: { handleItemTap(item){ console.log(this.getPageInstance().getUserId()) // '1' } } }) ``` ``` -------------------------------- ### Instance Method: getStore - Get Global Data Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Retrieves global data stored in the application's global scope, equivalent to accessing `getApp().globalData[key]`. This method can also be invoked using `wx.getStore`. ```js // app.js // App({ // globalData: { // count: 1 // } // }) ``` ```js // page.js // Page({ // handleTap() { // const count = this.getStore('count') // Equivalent to getApp().globalData.count // console.log(count) // 1 // } // }) ``` -------------------------------- ### Get Page URL Parameters Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Retrieves the query parameters from the current page's URL. The returned object is identical to the `options` parameter received in the page's `onLoad` lifecycle method. It's recommended to call this method after the component's `ready` lifecycle. ```APIDOC ***getUrlParams*** (): `object` 适用于: `component` 说明:获取当前组件所在页面的url参数,获取的结果同所在页面的生命周期`onLoad(options)`的回调参数`options`一致 注意: 请在组件的`ready`生命周期及其之后再获取url参数,在`created`、`attached`中无法获得正确结果 例子: ```js // pageA.js Page({ handleTap() { wx.navigateTo({ url: "/pages/detail/index?a=1&b=2" }) } }) ``` ```html ``` ```js // /pages/detail/index.js Page({ onLoad(options) { console.log(options.a) // '1' console.log(options.b) // '2' } }) ``` ```json /** /pages/detail/index.json **/ { "usingComponents": { "comA": "./comA/index" } } ``` ```js // ./comA/index.js Component({ lifetimes: { ready() { const urlParams = this.getUrlParams() console.log(urlParams.a) // '1' console.log(urlParams.b) // '2' } } }) ``` ``` -------------------------------- ### Get Sibling Component Instances Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Retrieves a list of all sibling component instances of the same type within the current page. This is useful for batch updates or state synchronization across multiple instances of a component without relying on global state. ```APIDOC ***getCognates*** (): `component[]` 适用于:`component` 说明:获取同胞组件实例列表 同胞组件指同一个组件在页面上有多个实例,某些场景下不想使用全局状态,又需要批量更新同类组件的状态 例子: ```xml 内容1 内容2 内容3 ``` `required-login`组件定义如下: ```xml 登录后才能查看 点击登录 ``` ```js // required-login.js Component({ data: { isLogin: false }, methods: { handleTap() { // 获取到所有required-login组件实例列表,并且批量更新它们的状态 this.getCognates().forEach(c => c.setData({ isLogin: true })) }, } }) ``` ``` -------------------------------- ### Page onInit Hook Usage Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Demonstrates how to implement the onInit hook within a page. This hook runs before onLoad and can delay page rendering by returning a Promise. ```javascript Page({ onInit(options) { return new Promise((resolve) => setTimeout(() => resolve(), 1000)) }, onLoad(options) { // 等待onInit钩子执行完毕我才会执行 }, onShow() { // 等待onInit钩子执行完毕我才会执行 }, onReady() { // 等待onInit钩子执行完毕我才会执行 } // ...其它钩子也会等待onInit钩子执行完毕才会执行 }) ``` -------------------------------- ### App Constructor: Asynchronous onLaunch Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Enables the App constructor's onLaunch hook to return a Promise, allowing for asynchronous initialization tasks that defer the loading of the entire app, pages, and components. Requires explicit configuration. ```js // app.js import wxbuf from 'wxbuf'; // Enable asynchronous onLaunch globally wxbuf.config({ asyncOnLaunch: true }); App({ async onLaunch() { // Ensure the returned Promise resolves successfully (Fulfilled state) try { const res = await fetch('/api/user'); // Process user data... } catch (e) { console.error('Failed to fetch user data:', e); // Handle error appropriately, but ensure the promise eventually resolves or rejects. } // The app, pages, and components will only proceed after this async onLaunch completes successfully. } }); /* Important: - If using asynchronous onLaunch, the returned Promise MUST eventually be in a 'Fulfilled' state. - If the Promise is rejected or never resolves, the app will not load. - The `asyncOnLaunch` configuration must be set before the App constructor is called. */ ``` -------------------------------- ### Component Instance Methods Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Methods available on a Component instance. These allow interaction with the parent page, URL parameters, sibling components, and the opener page. ```APIDOC getPageInstance(): pageInstance - Retrieves the instance of the current page. - Returns: The Page instance. getUrlParams(): object - Retrieves the URL parameters of the current page. - Can only be called after the 'ready' lifecycle hook. - Returns: An object containing the page's URL parameters. invoke(fnName: string, ...args: any[]): any - Attempts to call a method on the opener page of the current component. - Parameters: - fnName: The name of the method to call on the opener page. - ...args: Arguments to pass to the opener page's method. - Returns: The return value of the called method. getCognates(): component[] - Retrieves a list of sibling component instances. - Returns: An array of sibling component instances. ``` -------------------------------- ### App Constructor Options Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Configures the global application behavior by defining event listeners, data injection strategies, and various lifecycle hooks for pages and components. ```APIDOC App(option): option.listeners: Declare global event listeners. option.injectStore: Globally inject store into all instances (page, component). option.injectStorage: Globally inject storage into all instances (page, component). option.onStoreChange: Listen for global data (store) changes. option.onStorageChange: Listen for storage changes. option.beforePageEnter: Callback before a new page loads. option.onPageLoad: Callback during page onLoad. option.onPageShow: Callback during page onShow. option.onPageUnload: Callback during page onUnload. option.onPageInit: Page initialization hook, can return a promise to defer page/component loading. option.onPageShareAppMessage: Callback when a page is shared to friends, can intercept and modify parameters. option.onPageShareTimeline: Callback when a page is shared to moments, can intercept and modify parameters. option.onEventDispatch: Pre-interceptor for UI standard event triggers. option.onComponentCreated: Callback when a component is created. option.onComponentAttached: Callback when a component is attached. option.onComponentReady: Callback when a component is ready. option.onComponentDetached: Callback when a component is detached. option.onLaunch: Supports returning a promise to delay app, page, and component loading. ``` -------------------------------- ### Configure and Use app.onPageInit Hook Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Enables and demonstrates the global onPageInit hook in the application. This hook runs before any page's onInit, allowing for centralized initialization logic and deferral. ```javascript // app.js (Configuration) import wxbuf from 'wxbuf' wxbuf.config({ pageOnInit: true // 开启pageOnInit }) App({ //... }) ``` ```javascript // app.js (Usage) App({ onPageInit(options) { return new Promise((resolve) => setTimeout(() => resolve(), 1000)) }, }) ``` -------------------------------- ### Component onInit Hook Usage Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Shows how component lifecycle hooks are deferred until the parent page's onInit hook completes. This ensures components load after the page is ready. ```javascript Component({ pageLifetimes: { show() { // 等待页面的onInit钩子执行完毕我才会执行 }, hide() { // 等待页面的onInit钩子执行完毕我才会执行 } }, lifetimes: { create(options) { // 等待页面的onInit钩子执行完毕我才会执行 }, attached() { // 等待页面的onInit钩子执行完毕我才会执行 }, ready() { // 等待页面的onInit钩子执行完毕我才会执行 } // ...其它钩子也会等待页面onInit钩子执行完毕才会执行 } }) ``` -------------------------------- ### Basic c-text Usage Source: https://github.com/laivv/wxbuf/blob/master/examples/mini-app-demo/components/c-text/readme.md Demonstrates the fundamental usage of the c-text component to display a value. It shows how to pass a 'value' attribute to the component. ```xml ``` ```javascript Page({ data: { timeStamp: 1714123672808 } }) ``` -------------------------------- ### Global Methods and Configuration Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Provides access to application instances, saved page/tabbar instances, and global configuration options to customize framework behavior. ```APIDOC Global Methods & Configuration: getApplication(): AppInstance Gets the application instance. getSavedPages(): page[] Gets all un-destroyed page instances. getSavedTabBars(): component[] Gets the list of tab bar instances. wxbuf.config(option): option.parseUrlArgs: Whether to enable automatic deserialization of URL parameters. option.methodPrefix: Prefix to add to methods on wxbuf instances or the wx object. option.enableGlobalShareAppMessage: Whether to enable sharing to friends for all pages. option.enableGlobalShareTimeline: Whether to enable sharing to moments for all pages. option.storeKey: Specifies which key value is managed as global data (store), defaults to 'globalData'. ``` -------------------------------- ### Component Constructor Options Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Options for the Component constructor, enabling computed properties, event listeners, data mixing, lifecycle hooks, and data provision/injection. ```APIDOC computed: object - Declares computed properties for the component. listeners: object - Declares global event listeners. mixinStore: boolean - Enables reactive global data (store) mixing. mixinStorage: boolean - Enables reactive storage data mixing. onStoreChange: function - Listener for global data (store) changes. onStorageChange: function - Listener for storage changes. pageLifeTimes: object - Hooks for the parent page's lifecycle events: - pullDownRefresh: Corresponds to page's onPullDownRefresh. - reachBottom: Corresponds to page's onReachBottom. - pageScroll: Corresponds to page's onPageScroll. - switchTab: Called when the parent tab bar page triggers onSwitchTab. parentLifeTimes: object - Hooks for parent component lifecycle events: - setData: Called when the parent component calls this.setData. exports: object - Exposes methods to the parent component instance. provide: object - Provides data to descendant components. inject: object - Injects data provided by upper-level components (used with provide). ``` -------------------------------- ### Page Constructor Options Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Options that can be passed to the Page constructor to define its behavior, lifecycle, and data management. ```APIDOC computed: object - Declares computed properties for the page. observers: object - Declares watchers for field changes. listeners: object - Declares global event listeners. onWakeup: function - Callback function invoked when the page is shown again (not the first time). onSwitchTab: function - Callback function for tab bar pages when switching to the page for the second time or later; can receive parameters. mixinStore: boolean - Enables reactive global data (store) mixing. mixinStorage: boolean - Enables reactive storage data mixing. onStoreChange: function - Listener for global data (store) changes. onStorageChange: function - Listener for storage changes. provide: object - Provides data to descendant components. onInit: function - Page initialization hook. Can return a promise to defer page and component loading. ``` -------------------------------- ### Page Instance Methods Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Methods available on a Page instance. Includes invoking methods on the opener page and accessing page-specific information. ```APIDOC invoke(fnName: string, ...args: any[]): any - Attempts to call a method on the opener page. - Parameters: - fnName: The name of the method to call on the opener page. - ...args: Arguments to pass to the opener page's method. - Returns: The return value of the called method, or undefined if the method does not exist or cannot be called. ``` -------------------------------- ### Page and Component Navigation APIs Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md APIs for navigating between pages and managing the page stack. Includes opening new pages, replacing the current page, and finishing the current page. ```APIDOC openPage(option: object): promise - Opens a new page. - Parameters: - option: An object containing navigation parameters, potentially including the page path and data. - Returns: A promise that resolves when the new page is opened. replacePage(option: object): void - Opens a new page, replacing the current page in the navigation stack. - Parameters: - option: An object containing navigation parameters. - Returns: void. finish(value?: any): void - Closes the current page. - Parameters: - value?: Optional data to pass back to the previous page. - Returns: void. ``` -------------------------------- ### Storage Management APIs (Async) Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Asynchronous APIs for managing local storage. Includes setting, removing, and batch setting key-value pairs, as well as clearing the entire storage. ```APIDOC setStorage(option: object): void - Asynchronously sets data in local storage. - Parameters: - option: An object containing 'key' and 'data' properties. - Returns: void. removeStorage(option: object): void - Asynchronously removes data from local storage. - Parameters: - option: An object containing the 'key' to remove. - Returns: void. batchSetStorage(option: object): void - Asynchronously sets multiple key-value pairs in local storage. - Parameters: - option: An object containing a 'kvList' array of {key, data} objects. - Returns: void. clearStorage(): void - Asynchronously clears all data from local storage. - Returns: void. ``` -------------------------------- ### Instance Method: openPage - Navigate to Pages Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Opens a new page, serving as an alternative to `wx.navigateTo`. It supports navigation via a unique page `name` or a `url`. Parameters can be passed via `params` or `body`. It can also receive data back from the opened page using the `finish` method. ```ts type openPageOption = { // Page name, must be unique across the app. Mutually exclusive with url. name?: string, // Page url, must start with '/'. Mutually exclusive with name. url?: string, // Query parameters for the page, appended to the url. params?: {[key: string]: any }, // Use body to pass parameters instead of url (use with caution). body?: any, // Callback function upon successful navigation. 'page' is a proxy object for the opened page. success?: (page) => void } ``` ```js // Example using page name (experimental, only for main package pages) // /pages/detail/index.json // { // "name": "详情页", // Define unique page name // "navigationBarTitleText": "数据详情" // } // Open /pages/detail/index?id=123, passing body data // this.openPage({ // name: '详情页', // params: { id: "123" }, // body: { name: "wxbuf" } // Data passed via memory, not URL // }) // /pages/detail/index.js // Page({ // onLoad(option) { // console.log(option.id) // "123" // console.log(option.name) // "wxbuf" // } // }) ``` ```js // Example using url // this.openPage({ // url: '/pages/pagesB/index?name=wxbuf', // params: { id: '123' }, // Final URL: /pages/pagesB/index?name=wxbuf&id=123 // success(page) { // // Access opened page and set data // page.setData({ age: 18 }) // } // }) ``` ```js // Example receiving data back from opened page // pageA.js // Page({ // async handleTap() { // const acceptData = await this.openPage({ url: '/pages/detail/index' }) // console.log(acceptData) // '这是回传数据' // } // }) // pages/detail/index.js // Page({ // async handleOk() { // // Call finish to return data and close the current page // this.finish('这是回传数据') // } // }) ``` -------------------------------- ### Configure wxbuf Global Settings Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Sets global configuration options for wxbuf, such as URL parameter parsing, method prefixes, sharing settings, and store keys. This configuration is applied in the `app.js` file. ```js import wxbuf from 'wxbuf' wxbuf.config({ // 开启自动反序列化url参数 parseUrlArgs: true, // 给wxbuf提供的实例或wx对象上的方法添加前缀,用于防止冲突 methodPrefix: '', // 开启所有页面分享给好友(优先使用页面自己的分享函数) enableGlobalShareAppMessage: true, // 开启所有页面分享到朋友圈(优先使用页面自己的分享函数) enableGlobalShareTimeline: true, // 异步onLaunch, 当开启后,app中的onLaunch钩子可以return一个Promise来延迟加载页面 asyncOnLaunch: false, // 页面的onInit钩子支持, 开启后,页面中的onInit钩子可以return一个Promise来延迟加载页面 pageonInit: false, // 指定全局数据的key storeKey: 'globalData' }) App({ globalData: {}, onLaunch() {} // ... }) ``` -------------------------------- ### wx Object Utility Methods Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Provides enhanced utility methods for the wx object, offering alternatives to standard navigation and data management functions. These methods often mirror instance methods and are recommended for direct use. ```APIDOC wx.openPage(option: object): Promise - Opens a new page, similar to instance.openPage(). Can replace wx.navigateTo. - Parameters: - option: Object containing page navigation details. - Returns: A Promise. wx.replacePage(option: object): void - Opens a new page, replacing the current page in the stack, similar to instance.replacePage(). Can replace wx.redirectTo. - Parameters: - option: Object containing page navigation details. - Returns: void. wx.finish(value?: any): void - Closes the current page, similar to instance.finish(). Can replace wx.navigateBack. - Parameters: - value: Optional value to pass back. - Returns: void. wx.getStore(key: string): any - Retrieves global data by key, similar to instance.getStore(). Recommended over direct global data access. - Parameters: - key: The key of the global data to retrieve. - Returns: The stored data. wx.setStore(key: string, value: any): void - Modifies global data by key, similar to instance.setStore(). Recommended over direct global data access. - Parameters: - key: The key of the global data to set. - value: The new value for the global data. - Returns: void. wx.getNavigateBarTitle(): string - Gets the current page's navigation bar title. Not suitable for custom navigation bars. Accuracy may vary; recommended not to use. - Returns: The navigation bar title string. wx.getTabBarPages(): string[] - Retrieves a list of URLs for all tab bar pages. - Returns: An array of tab bar page URLs. wx.isTabBarPage(url: string): boolean - Checks if a given URL corresponds to a tab bar page. - Parameters: - url: The path URL to check. - Returns: true if the URL is a tab bar page, false otherwise. wx.getConfigJson(url: string): object - Retrieves the JSON file content for a given page. Currently only supports pages in the main package and is unstable; not recommended for use. - Parameters: - url: The URL of the page. - Returns: The JSON content object. wx.fireEvent(name: string, value?: any): void - Dispatches an event, functionally equivalent to instance.fireEvent(). - Parameters: - name: The name of the event to dispatch. - value: Optional value to pass with the event. - Returns: void. ``` -------------------------------- ### wxbuf Global Page/Component Method Extension Source: https://github.com/laivv/wxbuf/blob/master/docs/DOCS.md Demonstrates extending Page and Component instances with common methods using wxbuf.page.extend and wxbuf.component.extend. This allows reusable methods to be called directly on page or component instances. ```javascript // app.js import wxbuf from 'wxbuf' wxbuf.page.extend({ getData(key){ return this.data[key] } }) App({ globalData: {}, onLaunch() {} // ... }) ``` ```javascript // pageA.js Page({ data: { name: 'wxbuf is a library' }, onLoad() { const name = this.getData('name') console.log(name) // 'wxbuf is a library' } }) ``` -------------------------------- ### Configure wxbuf pageOnInit Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Enables the pageOnInit hook in the application's configuration. This allows pages to define an onInit method that runs before onLoad. ```javascript // app.js import wxbuf from 'wxbuf' wxbuf.config({ pageOnInit: true // 开启pageOnInit }) App({ //... }) ``` -------------------------------- ### Behavior Constructor Options Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Options for the Behavior constructor, similar to Component options, allowing for computed properties, event listeners, data mixing, and lifecycle hooks. ```APIDOC computed: object - Declares computed properties for the behavior. listeners: object - Declares global event listeners. mixinStore: boolean - Enables reactive global data (store) mixing. mixinStorage: boolean - Enables reactive storage data mixing. onStoreChange: function - Listener for global data (store) changes. onStorageChange: function - Listener for storage changes. pageLifeTimes: object - Hooks for the parent page's lifecycle events: - pullDownRefresh: Corresponds to page's onPullDownRefresh. - reachBottom: Corresponds to page's onReachBottom. - pageScroll: Corresponds to page's onPageScroll. ``` -------------------------------- ### wx Object Utility Methods Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Provides essential utility functions for navigating between pages, managing the page stack, accessing global data, and retrieving page information. ```APIDOC wx Object Methods: wx.openPage(option: object): promise Opens a new page. wx.replacePage(option: object): void Opens a new page, replacing the current one in the navigation stack. wx.finish(value?: any): void Closes the current page. wx.getStore(key: string): any Retrieves global data (store) by key. wx.setStore(key: string, value: any): any Sets global data (store) by key. wx.getNavigateBarTitle(): string Gets the title of the current page's navigation bar. wx.getTabBarPages(): string[] Gets the list of tab bar page paths. wx.isTabBarPage(url: string): boolean Checks if a given URL corresponds to a tab bar page. wx.getConfigJson(url: string): object Retrieves the raw JSON configuration file information for a page. wx.fireEvent(eventName: string, value: any): void Dispatches an event (similar to instance.fireEvent method). wx.switchTab(option: object): void Switches to a tab bar page. Now supports carrying query parameters in the URL. ``` -------------------------------- ### c-loading with Pagination Source: https://github.com/laivv/wxbuf/blob/master/examples/mini-app-demo/components/c-loading/readme.md Illustrates the pagination feature of the c-loading component. This mode automatically triggers the `loadData` callback not only when the page loads but also when the user scrolls to the bottom of the page, facilitating infinite scrolling or paginated data retrieval. ```wxml ``` ```js Page({ async getData() { await fetch('/user/list') } }) ``` -------------------------------- ### Extend Component Instances with wxbuf.component.extend Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Extends all component instances with custom methods, providing similar functionality to `wxbuf.page.extend`. This allows for consistent method additions across components. ```APIDOC wxbuf.component.extend(`option`: object): void Extends all component instances with custom methods. The effect is the same as `wxbuf.page.extend`. ``` -------------------------------- ### injectStore for Global Store Injection Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Option to globally inject globalData fields into all pages and components. It supports a namespace for prefixing and a list of keys to inject from globalData. ```javascript import wxbuf from 'wxbuf' App({ injectStore: { namespace: '$store', keys: ['appVersion', 'appCount'], }, globalData: { appVersion: 'v1.0', appCount: 0 }, onLaunch(){ } }) ``` ```xml {{$store.appCount}} {{$store.appVersion}} ``` ```javascript Page({ onLoad(){ console.log(this.data.$store) } }) ``` -------------------------------- ### WXML Usage of c-button Source: https://github.com/laivv/wxbuf/blob/master/examples/mini-app-demo/components/c-btn/readme.md Demonstrates the integration of the custom c-button component within a WXML file. It shows how to bind a click event handler and specify custom text for the loading state. ```xml 提交表单 ``` -------------------------------- ### Global Utility Functions Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Provides global utility functions for accessing application instances and page information, offering alternatives to built-in methods with specific advantages. ```APIDOC getApplication(): AppInstance - Retrieves the application instance. Similar to the built-in `getApp()`, but correctly returns the instance even within the `App`'s `onLaunch` hook where `getApp()` might return `undefined`. - Returns: The application instance. getSavedPages(): page[] - Retrieves all non-destroyed page instances. This differs from `getCurrentPages()` which returns the current page stack. `getSavedPages()` can access pages that have been opened multiple times (e.g., tab bar pages) and are not currently in the foreground stack. - Returns: An array of page instances. ``` -------------------------------- ### Instance Method: replacePage - Redirect to Page Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Opens a new page by replacing the current one in the navigation stack, similar to `wx.redirectTo`. It supports navigation via page `name` or `url`, and allows passing parameters through `params` or `body`. ```js // this.replacePage({ // url: '/pages/pagesB/index', // params: { id: 'xxx' }, // }) ``` -------------------------------- ### c-text Usage with Filter Parameters Source: https://github.com/laivv/wxbuf/blob/master/examples/mini-app-demo/components/c-text/readme.md Demonstrates passing additional arguments to the filter function via the 'params' attribute. These parameters are appended to the arguments passed to the filter function. ```xml ``` ```javascript Page({ data: { timeStamp: 1714123672808 }, formatDate(value, format) { return dayjs(value).format(format) } }) ``` -------------------------------- ### injectStorage for Global Storage Injection Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Option to globally inject storage data into all pages and components. It allows specifying a namespace and the keys from storage to be injected. ```javascript import wxbuf from 'wxbuf' App({ injectStorage: { namespace: '$storage', keys: ['count'], }, onLaunch(){ } }) ``` ```xml {{$storage.count}} ``` ```javascript Page({ onLoad(){ console.log(this.data.$storage) } }) ``` -------------------------------- ### Cross-level Data Passing with Provide/Inject Source: https://github.com/laivv/wxbuf/blob/master/docs/DOCS.md Demonstrates how wxbuf enables cross-level data passing in WeChat Mini Programs using a provide/inject mechanism similar to Vue. It covers both static and reactive data sharing between components. ```javascript // Host Page (Static Provide) Page({ provide: { rootName: '这是page数据', rootFn() { console.log('this is rootFn') } } }) // Child Component Component({ inject: ['rootName', 'rootFn'], lifetimes: { attached(){ console.log(this.data.rootName) // '这是page数据' this.rootFn() // 'this is rootFn' } } }) ``` ```javascript // Host Page (Reactive Provide) Page({ data: { number: 1 }, provide() { return { pageNumber: this.data.number } } }) // Child Component Component({ inject: ['pageNumber'], lifetimes: { attached(){ console.log(this.data.pageNumber) // 1 } } }) ``` -------------------------------- ### Storage Management APIs Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Provides asynchronous and synchronous methods for managing local storage, including setting, removing, and clearing data. These methods are designed to be drop-in replacements for WeChat's built-in storage APIs. ```APIDOC ***setStorage*** (`option`: object): `void` 适用于: `app` 、`page`、 `component`、 `behavior` 说明:异步设置`storage`, 可代替`wx.setStorage` ***removeStorage*** (`option`: object): `void` 适用于: `app` 、`page`、 `component`、 `behavior` 说明:异步移除某个`storage`, 可代替`wx.removeStorage` ***getStorageSync*** (`key`: string): `any` 适用于: `app` 、`page`、 `component`、 `behavior` 说明:同步获取`storage`, 可代替`wx.getStorageSync` ***setStorageSync*** (`key`: string, `value`: any): `void` 适用于: `app` 、`page`、 `component`、 `behavior` 说明:同步设置`storage`, 可代替`wx.setStorageSync` ***removeStorageSync*** (`key`: string): `void` 适用于: `app` 、`page`、 `component`、 `behavior` 说明:同步移除某个`storage`, 可代替`wx.removeStorageSync` ***batchSetStorage*** (`option`: object): `void` 适用于: `app` 、`page`、 `component`、 `behavior` 说明:异步批量设置`storage`, 可代替`wx.batchSetStorage` ***batchSetStorageSync*** (`kvList`: array): `void` 适用于: `app` 、`page`、 `component`、 `behavior` 说明:同步批量设置`storage`, 可代替`wx.batchSetStorageSync` ***clearStorage*** (): `void` 适用于: `app` 、`page`、 `component`、 `behavior` 说明:异步清空`storage`, 可代替`wx.clearStorage` ***clearStorageSync*** (): `void` 适用于: `app` 、`page`、 `component`、 `behavior` 说明:同步清空`storage`, 可代替`wx.clearStorageSync` ``` -------------------------------- ### Mixin Storage: Basic Usage Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Demonstrates how to use mixinStorage to synchronize storage keys with component data. When storage data changes, the component's data is automatically updated, and vice-versa through provided methods. ```APIDOC mixinStorage: array Applies to: page, component, behavior Description: Automatically syncs storage data to the current instance's data fields and maintains consistency. Useful for scenarios where the view needs to update automatically based on storage changes. Parameters: - array: An array of storage keys to synchronize. If a key name conflicts with an instance's data field, it can be renamed using the 'key->newKey' format. Example: // Assuming storage has count=1, isLogin=true // page.js Page({ mixinStorage: ['count', 'isLogin'], onLoad() { console.log(this.data.count) // 1 console.log(this.data.isLogin) // true }, handleTap() { this.setStorageSync('count', 2) console.log(this.data.count) // 2 console.log(this.getStorageSync('count')) // 2 console.log(wx.getStorageSync('count')) // 2 } }) ``` ```js Page({ mixinStorage: ['count', 'isLogin'], onLoad() { console.log(this.data.count) // 1 console.log(this.data.isLogin) // true }, handleTap() { this.setStorageSync('count', 2) console.log(this.data.count) // 2 console.log(this.getStorageSync('count')) // 2 console.log(wx.getStorageSync('count')) // 2 } }) ``` -------------------------------- ### Component Instance Properties Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Properties available on a Component instance, providing access to its parent, page, and route information. ```APIDOC $parent: object - Reference to the parent component instance. $page: object - Reference to the current page instance. $route: string - The URL path of the current page. ``` -------------------------------- ### Global Listeners with wxbuf.watch Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Allows registration of global listeners for various application and page lifecycle events, enabling centralized event handling. ```APIDOC wxbuf.watch(option): option.onAppLaunch: Listener for application launch. option.onAppShow: Listener for application show. option.onAppHide: Listener for application hide. option.onPageLoad: Listener for page load. option.onPageShow: Listener for page show. option.onPageScroll: Listener for page scroll. option.onPageReachBottom: Listener for page reach bottom. option.onPagePullDownRefresh: Listener for page pull down refresh. option.onTap: Listener for tap events. option.onLongtap: Listener for long tap events. option.onLongpress: Listener for long press events. option.onTouchstart: Listener for touch start events. option.onTouchmove: Listener for touch move events. option.onTouchend: Listener for touch end events. option.onTouchcancel: Listener for touch cancel events. option.onTouchforcechange: Listener for touch force change events. option.onInput: Listener for input events. option.onFocus: Listener for focus events. option.onBlur: Listener for blur events. option.onConfirm: Listener for confirm events. ``` -------------------------------- ### wxbuf Features in a Page (pages/login/index.js) Source: https://github.com/laivv/wxbuf/blob/master/readme.md Demonstrates how to leverage wxbuf features within a specific page (pages/login/index.js). This includes synchronizing global store and storage data, defining observers for data changes, using computed properties, and handling page events like taps with data passing and page closing. ```javascript // pages/login/index.js Page({ // Declare event listeners listeners: {}, // Synchronize global data mixinStore: [ 'isLogin', // Conflict with current page data field, rename here 'version -> appVersion' ], // Synchronize storage, assuming token field in storage has value 'abc' mixinStorage: ['token'], // Storage change listener onStorageChange(kvs, oldKvs){ }, // Global data change listener onStoreChange(kvs, oldKvs){ }, data: { total: 1, version: 'page-v0.5' }, // Field change listener observers: { total(curVal, oldVal) { console.log('this.data.total has been modified', curVal, oldVal) } }, // Computed properties computed: { totalText() { return `Total: ${this.data.total} items` } }, onLoad() { console.log(this.data.isLogin) // false console.log(this.data.token) // 'abc' console.log(this.data.totalText) // 'Total: 1 items' console.log(this.data.version) // 'page-v0.5' console.log(this.data.appVersion) // 'app-v1.0' }, handleTap() { if(!this.data.isLogin) { const token = await fetch('/login') // Dispatch an event this.fireEvent('loginOk', token) // Modify storage this.setStorageSync('token', token) // Close page and pass data back this.finish('This message will be returned') } } // ... }) ``` -------------------------------- ### provide Option for Data Provision Source: https://github.com/laivv/wxbuf/blob/master/docs/APIS.md Allows a page or component to provide data to its descendants. This can be a static object or a function returning an object, facilitating cross-level data transmission. ```javascript Page({ provide: { rootName: '这是page数据' } }) ``` ```javascript Page({ provide() { return { rootName: '这是page数据' } } }) ``` -------------------------------- ### wx.switchTab Parameter Passing Source: https://github.com/laivv/wxbuf/blob/master/docs/DOCS.md Demonstrates how to pass query parameters to a tab bar page using wx.switchTab. It explains how to receive these parameters in the target page's onLoad and onSwitchTab lifecycle methods. ```javascript // /pageA.js Page({ // 第一次点击 handleFirstTap() { wx.switchTab({ url: '/pages/my/index?a=1' }) }, // 第二次点击 handleSecondTap() { wx.switchTab({ url: '/pages/my/index?a=2' }) }, }) ``` ```javascript // /pages/my/index.js // 此页面是tabbar页面 Page({ // 首次进入页面在onLoad钩子接收wx.switchTab参数 onLoad(options) { console.log(options.a) // '1' }, // 非首次进入页面在onSwitchTab钩子接收wx.switchTab参数 onSwitchTab(options) { console.log(options.a) // '2' } }) ```