### Setup Function Example Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/basic/component.md Illustrates the use of the setup function with Composition API, including refs and lifecycle hooks. ```javascript import { createComponent, ref, onMounted, onUnmounted } from '@mpxjs/core' createComponent({ properties: { user: String, }, setup(props) { const repositories = ref([]) const getUserRepositories = async () => { repositories.value = await fetchUserRepositories(props.user) } // 注册生命周期钩子 onMounted(() => { console.log('Component mounted.') getUserRepositories() }) onUnmounted(() => { console.log('Component unmounted.') }) return { repositories, getUserRepositories, } }, }) ``` -------------------------------- ### Install and Run Project Source: https://github.com/didi/mpx/blob/master/examples/mpx-webview/README.md Install project dependencies and run the development server. This command builds the project for cross-platform output and starts a local HTTP server to host the H5 resources. ```bash npm i npm run dev ``` -------------------------------- ### Using ` ``` -------------------------------- ### Registering lifecycle hooks in setup with onMounted Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/composition-api/composition-api.md Demonstrates how to register lifecycle hooks within the `setup` function using Mpx's provided hook functions, which start with `on`. This example uses `onMounted` to call `getUserRepositories` when the component is mounted, corresponding to the `ready` hook in native WeChat Mini Programs. ```javascript import { createComponent, ref, onMounted } from '@mpxjs/core' import { fetchUserRepositories } from '@/api/repositories' createComponent({ properties: { user: String }, setup (props) { let repositories = ref([]) const getUserRepositories = async () => { repositories.value = await fetchUserRepositories(props.user) } onMounted(getUserRepositories) return { repositories, getUserRepositories } } }) ``` -------------------------------- ### Navigate and Install Dependencies Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/cli.md After project creation, change into the project directory and install the necessary dependencies. ```bash cd my-project npm install ``` -------------------------------- ### Install and Initialize Mpx CLI Source: https://github.com/didi/mpx/blob/master/packages/core/README.md Install the Mpx CLI tool globally, then use it to create a new Mpx project. Navigate into the project directory and install dependencies. ```bash npm i -g @mpxjs/cli mpx create mpx-project cd mpx-project npm i ``` -------------------------------- ### Install, Watch, and Build Commands Source: https://github.com/didi/mpx/blob/master/examples/mpx-cloud/README.md Standard npm commands for installing dependencies, running the development server, and building for production. ```bash npm i npm run watch npm run product ``` -------------------------------- ### Web Configuration Example Source: https://github.com/didi/mpx/blob/master/solutions/register-custom-builtin.md Example of configuring custom built-in components within the web configuration object. ```javascript webConfig.customBuiltInComponents ``` -------------------------------- ### Start Performance Recording Window Source: https://github.com/didi/mpx/blob/master/solutions/rn-runtime-perf-probe.md Initiates a performance recording window. Any performance metrics captured between `start()` and `end()` will be recorded. This example shows its use in a route hook. ```typescript import { start, end } from '@mpxjs/perf' router.beforeEnter('/goods/:id', () => { if (__mpx_perf__) start() }) router.beforeLeave('/goods/:id', () => { if (__mpx_perf__) end() // end 内部同步触发 reporter,console 立即看到聚合表 }) ``` -------------------------------- ### Installing Dependencies for API Proxy Usage Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/rn/application-api.md Illustrates how to install specific native dependencies required by certain cross-platform APIs when using @mpxjs/api-proxy. Remember to run `pod install` for iOS projects with native dependencies. ```bash # 示例:只使用存储和设备信息API npm install @react-native-async-storage/async-storage react-native-device-info # 示例:使用位置服务 npm install react-native-get-location # 示例:使用网络状态监听 npm install @react-native-community/netinfo # iOS 项目需要执行(有原生依赖时) cd ios && pod install ``` -------------------------------- ### Using setup with Props Source: https://github.com/didi/mpx/blob/master/docs-vitepress/api/composition-api.md The setup function is the entry point for the Composition API. It is executed before the component is created and after props are resolved. Props are available as the first argument. ```js import { createComponent } from '@mpxjs/core' createComponent({ properties: { min: { type: Number, value: 0 }, lastLeaf: { // 这个属性可以是 Number 、 String 、 Boolean 三种类型中的一种 type: Number, optionalTypes: [String, Object], value: 0 } }, setup(props) { console.log(props.min) console.log(props.lastLeaf) } }) ``` -------------------------------- ### Start Development Server Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/cli.md Run the development server to start building your project. It automatically rebuilds on file changes. The default output directory is 'dist/wx'. ```bash npm run serve ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/didi/mpx/blob/master/examples/mpx-subpackage/README.md Use these npm commands to install project dependencies and build the project for development. ```bash npm i npm run build ``` -------------------------------- ### Mpx Lifecycle Hooks in Setup Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/composition-api/composition-api.md Provides an example of using `onMounted` and `onUnmounted` lifecycle hooks within the `setup` function in Mpx. These hooks allow you to run logic when the component is mounted or unmounted. ```javascript import { createComponent, onMounted, onUnmounted } from '@mpxjs/core' createComponent({ setup () { // mounted onMounted(()=>{ console.log('Component mounted.') }) // unmounted onUnmounted(()=>{ console.log('Component unmounted.') }) return {} } }) ``` -------------------------------- ### setup Function Source: https://github.com/didi/mpx/blob/master/docs-vitepress/api/composition-api.md The `setup` function is called before the component's props are resolved. It serves as the entry point for the Composition API and receives props and context as arguments. ```APIDOC ## setup A component option that executes before the component is created and after props are resolved. It is the entry point for the Composition API. ### Parameters - `{Data} props`: An object containing declared properties. All declared props, whether passed by the parent or not, will be present in the `props` object. Optional props not passed will have their default value or `undefined`. - `{SetupContext} context`: An object providing access to various component instance functionalities. ### Example ```js import { createComponent } from '@mpxjs/core' createComponent({ properties: { min: { type: Number, value: 0 }, lastLeaf: { type: Number, optionalTypes: [String, Object], value: 0 } }, setup(props) { console.log(props.min) console.log(props.lastLeaf) } }) ``` ### Type Declaration ```ts interface SetupContext { triggerEvent(name: string, detail?: object, options?: { bubbles?: boolean, composed?: boolean, capturePhase?: boolean }): void refs: ObjectOf asyncRefs: ObjectOf> // Specific to ByteDance Mini Program nextTick: (fn: () => void) => void forceUpdate: (params?: object, callback?: () => void) => void selectComponent(selector: string): ComponentIns selectAllComponents(selector: string): ComponentIns[] createSelectorQuery(): SelectorQuery createIntersectionObserver(options: { thresholds?: Array, initialRatio?: number, observeAll?: boolean }): IntersectionObserver } function setup(props: Record, context: SetupContext): Record ``` ``` -------------------------------- ### Define Setup Store Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/pinia.md Create a store using the Setup style, similar to Vue's Composition API. `ref` for state, `computed` for getters, and functions for actions. ```js // setup.js import { defineStore } from '@mpxjs/pinia' import { ref, computed } from '@mpxjs/core' export const useSetupStore = defineStore('setup', () => { const count = ref(0) const name = ref('pinia') const myName = computed(() => { return name.value }) function increment() { count.value++ } return { count, name, myName, increment } }) ``` -------------------------------- ### Basic setup function in Mpx Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/composition-api/composition-api.md Demonstrates the basic structure of a `setup` function within `createComponent`. It initializes a non-reactive `repositories` variable and an async function `getUserRepositories` to fetch data. The returned values can be accessed in other component options or templates. ```javascript import { createComponent } from '@mpxjs/core' import { fetchUserRepositories } from '@/api/repositories' createComponent({ properties: { user: String }, setup (props) { let repositories = [] const getUserRepositories = async () => { repositories = await fetchUserRepositories(props.user) } return { repositories, getUserRepositories } } }) ``` -------------------------------- ### Install webview-bridge Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/extend/webview-bridge.md Install the library using npm. This package provides a unified interface for H5-to-miniapp communication. ```shell npm install @mpxjs/webview-bridge ``` -------------------------------- ### Install E2E SDK and Runner Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/tool/e2e-test.md Install the necessary E2E SDK and runner packages as development dependencies for an existing project. ```bash npm i @mpxjs/e2e @mpxjs/e2e-scripts --save-dev ``` -------------------------------- ### Install Mpx CLI Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/tool/e2e-test.md Install the Mpx CLI globally to scaffold new projects. ```bash $ npm install -g @mpxjs/cli ``` -------------------------------- ### Mpx Setup with Template Binding Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/composition-api/composition-api.md Illustrates how to expose reactive data and methods from the `setup` function to the template in Mpx by returning an object. This allows template access to `readersNumber` and `book` properties. ```html ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/basic/start.md After creating a new Mpx project and configuring it, navigate into the project directory and install its dependencies using npm. ```shell npm install ``` -------------------------------- ### Mpx DllPlugin Configuration Example Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/dll-plugin.md Configure DllPlugin for Mpx projects in `build/dll.config.js`. This example shows how to set up cache groups for different platforms (wx, ali) and specify entry points and output names. ```javascript const path = require('path') // 这里是一个用法示例 function resolve (file) { return path.resolve(__dirname, '..', file || '') } module.exports = [ { cacheGroups: [ { entries: [resolve('node_modules/@someNpmGroup/someNpmPkgName/dist/wx/static/js/common.js')], name: 'test', root: 'testSomeDllFile' }, ], modes: ['wx'], entryOnly: true, format: true, webpackCfg: { mode: 'none', // 不使用任何默认优化选项 } }, { cacheGroups: [ { entries: [resolve('node_modules/@someNpmGroup/someNpmPkgName/dist/ali/static/js/common.js')], name: 'test', root: 'testSomeDllFile' }, ], modes: ['ali'], entryOnly: true, format: true, webpackCfg: { mode: 'none', // 不使用任何默认优化选项 } } ] ``` -------------------------------- ### Install Utility-First CSS Dependencies Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/utility-first-css.md Install the necessary dependencies for enabling utility-first CSS support in older Mpx projects. ```json { //... "devDependencies": { "@mpxjs/unocss-base": '^2.9.0', "@mpxjs/unocss-plugin": '^2.9.0' } } ``` -------------------------------- ### Background Shorthand Expansion Example 2 Source: https://github.com/didi/mpx/blob/master/solutions/rn-runtime-shorthand-style.md Demonstrates another example of `background` shorthand expansion, handling different values for position and size, including units and keywords. ```css background: 'url(bg.png) no-repeat left top / 100% 50%' // => backgroundImage: 'url(bg.png)' backgroundRepeat: 'no-repeat' backgroundPosition: ['left', 'top'] backgroundSize: ['100%', '50%'] ``` -------------------------------- ### Mpx Project Configuration Example Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/cli.md Configure project settings, webpack, and Mpx plugin options in the 'vue.config.js' file. This example shows output directory configuration and Mpx plugin options. ```javascript // vue.config.js module.exports = { outputDir: `dist/${process.env.MPX_CURRENT_TARGET_MODE || 'wx'}`, pluginOptions: { mpx: { // Mpx 插件配置 srcMode: 'wx', // 源码模式,默认为 wx plugin: { // mpx-webpack-plugin 配置 hackResolve: true }, loader: { // mpx-loader 配置 } } }, configureWebpack: { // 自定义 webpack 配置 resolve: { alias: { '@': 'src' } } } } ``` -------------------------------- ### Install Mpx CLI Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/basic/start.md Install the Mpx command-line interface globally using npm, pnpm, or yarn. ```sh npm i -g @mpxjs/cli ``` ```sh pnpm add -g @mpxjs/cli ``` ```sh yarn global add @mpxjs/cli ``` -------------------------------- ### Install Mpx CLI Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/plugin.md Globally install the Mpx CLI to create new Mpx projects, including plugin projects. ```sh npm i -g @mpxjs/cli ``` -------------------------------- ### Component Methods Example Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/basic/component.md Demonstrates how to declare and use methods within a component. ```javascript createComponent({ methods: { handleClick() { // 访问数据 console.log(this.message) // 调用其他方法 this.otherMethod() }, otherMethod() { // ... }, }, }) ``` -------------------------------- ### CSS px to rpx Conversion Example Source: https://github.com/didi/mpx/blob/master/docs-vitepress/api/compile.md Illustrates the conversion of px values to rpx based on the designWidth. The example shows how px values are multiplied by a calculated transRatio to produce the final rpx values. ```css /* 转换前:designWidth = 1280 */ .btn { width: 200px; height: 100px; } /* 转换后: transRatio = 0.59 */ .btn { width: 118rpx; height: 59rpx; } ``` -------------------------------- ### RN Configuration Example Source: https://github.com/didi/mpx/blob/master/solutions/register-custom-builtin.md Example of configuring custom built-in components within the RN configuration object, allowing for platform-specific module paths. ```javascript rnConfig.customBuiltInComponents ``` -------------------------------- ### MPX Page Configuration Example Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/basic/page.md Example of how to configure MPX page properties like navigation bar colors, title, and background styles within a script tag. ```json ``` -------------------------------- ### Mpx Single File Component Example Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/basic/single-file.md This example demonstrates the structure of a .mpx file, which includes sections for template, script, style, and JSON configuration, corresponding to the native小程序 file types. ```html ``` -------------------------------- ### Setup Function Optional Prop Access with toRef Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/composition-api/composition-api.md Access optional props within the `setup` function using `toRef` when `toRefs` might not create a ref if the prop is missing. ```js import { createComponent, toRef } from '@mpxjs/core' createComponent({ props: { title: String }, setup(props) { const title = toRef(props, 'title') // `title` is a ref console.log(title.value) } }) ``` -------------------------------- ### E2E Test Case Example (list.spec.js) Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/tool/e2e-test.md Example of an end-to-end test case using the @mpxjs/e2e library. It demonstrates connecting to or launching the mini program, navigating pages, interacting with elements, and taking screenshots. ```javascript /** * @file e2e test example * 首先开启工具安全设置中的 CLI/HTTP 调用功能 * docs of miniprogram-automator: https://developers.weixin.qq.com/miniprogram/dev/devtools/auto/quick-start.html */ import automator from '@mpxjs/e2e' describe('index', () => { let miniProgram let page beforeAll(async () => { try { miniProgram = await automator.connect({ wsEndpoint: 'ws://localhost:9420' }) } catch (e) { miniProgram = await automator.launch({ projectPath: './dist/wx' }) } page = await miniProgram.reLaunch('/pages/index') await page.waitFor(500) }, 30000) it('desc', async () => { const desc = await page.$('list', 'components/list2271575d/index') // 断言页面标签 expect(desc.tagName).toBe('view') // 断言文字内容 expect(await desc.text()).toContain('手机') // 保存页面快照 await miniProgram.screenshot({ path: 'test/e2e/screenshot/homePage.png' }) }) afterAll(async () => { await miniProgram.close() }) }) ``` -------------------------------- ### Mpx Component Example Source: https://github.com/didi/mpx/blob/master/README.md A comprehensive Mpx component example demonstrating dynamic styles, data binding, computed properties, event handling, custom components, dynamic components, conditional rendering, and environment-specific templates. ```html ``` -------------------------------- ### Integrate and Start SSR Service with Express Source: https://github.com/didi/mpx/blob/master/docs-vitepress/articles/2.9-release.md Example of integrating Mpx SSR with an Express server. Ensure you have the necessary server and client bundle files generated by vue-server-renderer plugins. ```javascript //server.js const app = require('express')() const { createBundleRenderer } = require('vue-server-renderer') // 通过 vue-server-renderer/server-plugin 生成的文件 const serverBundle = require('../dist/server/vue-ssr-server-bundle.json') // 通过 vue-server-renderer/client-plugin 生成的文件 const clientManifest = require('../dist/client/vue-ssr-client-manifest.json') // 页面模版文件 const template = require('fs').readFileSync('../src/index.template.html', 'utf-8') // 创建 renderer 渲染器 const renderer = createBundleRenderer(serverBundle, { runInNewContext: false, template, clientManifest, }); // 注册启动 SSR 服务 app.get('*', (req, res) => { const context = { url: req.url } renderer.renderToString(context, (err, html) => { if (err) { res.status(500).end('Internal Server Error') return } res.end(html); }) }) app.listen(8080) ``` -------------------------------- ### Get Context with useContext Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/composition-api/composition-api.md Obtain the context object within ` ``` -------------------------------- ### Manually Add MpxUnocssPlugin to Webpack Source: https://github.com/didi/mpx/blob/master/docs-vitepress/api/compile.md If Unocss was not selected during project setup, manually install @mpxjs/unocss-plugin and add MpxUnocssPlugin to the webpack plugins. This involves importing the plugin and instantiating it with configuration options. ```js // vue.config.js const MpxUnocssPlugin = require('@mpxjs/unocss-plugin') const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ configureWebpack: { plugins: [ new MpxUnocssPlugin({ // @mpxjs/unocss-plugin 相关的配置 }) ] }, }) ``` -------------------------------- ### Define Exposed Variables with defineExpose Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/composition-api/composition-api.md Use defineExpose in ` ``` -------------------------------- ### Install @mpxjs/cli Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/cli.md Globally install the Mpx CLI tool using npm. Ensure Node.js version 10 or higher is installed. ```bash npm install -g @mpxjs/cli ``` -------------------------------- ### SSR App Initialization with Pinia Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/ssr.md Example of using the `onAppInit` lifecycle hook in `app.mpx` to create and return a new Pinia instance for each request, preventing cross-request state pollution. ```javascript // app.mpx import mpx, { createApp } from '@mpxjs/core' import { createPinia } from '@mpxjs/pinia' createApp({ // ... onAppInit () { const pinia = createPinia() return { pinia } } }) ``` -------------------------------- ### Initialize Mpx Project with E2E Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/tool/e2e-test.md Initialize a new Mpx project and select the option to include E2E testing during setup. ```bash $ mpx init some-proj ``` -------------------------------- ### Component Relations Example (Parent) Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/basic/component.md Example of a 'custom-li' component defining its parent ('custom-ul') and its linked callback. ```javascript // custom-li 组件 import { createComponent } from '@mpxjs/core' createComponent({ relations: { './custom-ul': { type: 'parent', // 关联的目标节点应为父节点 linked(target) { // 每次被插入到 custom-ul 时执行 console.log('ul linked', target) }, }, }, }) ``` -------------------------------- ### Serve Specific Platforms Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/cli.md Use platform-specific scripts to start the development server for different target platforms. ```bash npm run serve:ali # 支付宝小程序 ``` ```bash npm run serve:swan # 百度小程序 ``` ```bash npm run serve:tt # 字节跳动小程序 ``` ```bash npm run serve:web # Web 平台 ``` -------------------------------- ### Component Relations Example (Child) Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/basic/component.md Example of a 'custom-ul' component defining its children ('custom-li') and their lifecycle callbacks. ```javascript // custom-ul 组件 import { createComponent } from '@mpxjs/core' createComponent({ relations: { './custom-li': { type: 'child', // 关联的目标节点应为子节点 linked(target) { // 每次有 custom-li 被插入时执行 console.log('li linked', target) }, unlinked(target) { // 每次有 custom-li 被移除时执行 console.log('li unlinked', target) }, }, }, }) ``` -------------------------------- ### Example Configuration for Partial Compilation Source: https://github.com/didi/mpx/blob/master/solutions/support-component-partial-compile.md This configuration defines include rules for pages and components, specifying which paths should be considered for partial compilation. ```json partialCompileRules: { pages: { include: /pages\/demo/ }, components: { include: /components\/keep/ } } ``` -------------------------------- ### Registering Subpackages with Packages Syntax Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/subpackage.md This example shows how to register a subpackage using the 'packages' syntax by appending `?root=xxx` to the package path. The 'root' value defines the subpackage name. ```html // @file src/app.mpx // @file src/packages/index.mpx (子包的入口文件) ``` -------------------------------- ### JSON Output Example Source: https://github.com/didi/mpx/blob/master/docs-vitepress/articles/mpx2.md This is an example of the JSON output generated by the MPX2 single file generation process, containing component configurations. ```json { "usingComponents": { "list": "/components/list397512ea/list" } } ``` -------------------------------- ### Create a Simple Mpx Store Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/store.md Create a store instance with initial state and mutations using `createStore`. Export the store for use in other modules. ```javascript import {createStore} from '@mpxjs/core' const store = createStore({ state: { count: 0 }, mutations: { increment (state) { state.count++ } } }) export default store ``` -------------------------------- ### Install External Plugin Source: https://github.com/didi/mpx/blob/master/docs-vitepress/api/global-api.md Installs an external plugin into the Mpx application. Supports multiple parameters and optional prefix/postfix configuration for plugin properties. ```javascript import mpx from '@mpxjs/core' import test from './test' mpx.use(test) mpx.use(test, {prefix: 'mpx'}, 'otherparams') ``` -------------------------------- ### Registering Main Package Pages with Packages Syntax Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/subpackage.md This example demonstrates how to use Mpx's 'packages' syntax to register main package pages. It references an external Mpx file which contains its own 'pages' configuration, merging them into the main package. ```html // @file src/app.mpx // @file src/packages/index.mpx // 注意确保页面路径的唯一性 ``` -------------------------------- ### Start Mpx E2E Platform Service Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/tool/e2e-test.md Command to start the Mpx-E2E platform service, which is required for generating and managing E2E test cases. ```bash npm run e2eServe ``` -------------------------------- ### Basic Usage Source: https://github.com/didi/mpx/blob/master/docs-vitepress/api-proxy/index.md Demonstrates how to import and use the apiProxy with Mpx. ```APIDOC ## Basic Usage ```js import mpx from "@mpxjs/core" import apiProxy from "@mpxjs/api-proxy" mpx.use(apiProxy, options) ``` ``` -------------------------------- ### Install Unit Testing Dependencies Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/tool/unit-test.md Install necessary npm packages for unit testing Mpx projects. If using TypeScript, ts-jest is also required. ```bash npm i -D @mpxjs/mpx-jest @mpxjs/miniprogram-simulate jest babel-jest // 如果项目使用了ts,则还需要安装 npm i -D ts-jest ``` -------------------------------- ### Setup Function Props Access Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/composition-api/composition-api.md Access component props directly within the `setup` function. Props are reactive and should not be destructured directly to maintain reactivity. ```js import { createComponent } from '@mpxjs/core' createComponent({ props: { title: String }, setup(props) { console.log(props.title) } }) ``` -------------------------------- ### Create a New Mpx Project Source: https://github.com/didi/mpx/blob/master/docs-vitepress/guide/advance/cli.md Initialize a new Mpx project with the 'create' command. The CLI will guide you through project configuration via interactive prompts. ```bash mpx create my-project ``` -------------------------------- ### mpx.use Source: https://github.com/didi/mpx/blob/master/docs-vitepress/api/global-api.md Installs external extensions and supports multiple arguments. It allows for prefixing or postfixing plugin properties. ```APIDOC ## mpx.use ### Description Installs external extensions and supports multiple arguments. It allows for prefixing or postfixing plugin properties. ### Parameters #### plugin - **plugin** - Required - The external extension to install. #### options - **options** (object) - Optional - An object that can contain `prefix` or `postfix` to modify the plugin's properties. ### Usage ```js import mpx from '@mpxjs/core' import test from './test' mpx.use(test) mpx.use(test, {prefix: 'mpx'}, 'otherparams') ``` ``` -------------------------------- ### Mpx Store and Component Integration Example Source: https://github.com/didi/mpx/blob/master/docs-vitepress/api/store-api.md Demonstrates integrating a Mpx store created with `createStoreWithThis` into a Mpx component. It shows how to map state and actions from the store to component computed properties and methods, and how data from `data`, `mixin`, and `computed` are available via `this`. ```js import {createComponent, getMixin, createStoreWithThis} from '@mpxjs/core' const store = createStoreWithThis({ state: { aa: 1, bb: 2 }, getters: { cc() { return this.state.aa + this.state.bb } }, actions: { doSth3() { console.log(this.getters.cc) return false } } }) createComponent({ data: { a: 1, b: '2' }, computed: { c() { return this.b }, d() { // data, mixin, computed中定义的数据能够被推导到this中 return this.a + this.aaa + this.c }, // 从store上map过来的计算属性或者方法同样能够被推导到this中 ...store.mapState(['aa']) }, mixins: [ // 使用mixins,需要对每一个mixin子项进行getMixin辅助函数包裹,支持嵌套mixin getMixin({ computed: { aaa() { return 123 } }, methods: { doSth() { console.log(this.aaa) return false } } }) ], methods: { doSth2() { this.a++ console.log(this.d) console.log(this.aa) this.doSth3() }, ...store.mapActions(['doSth3']) } }) ``` -------------------------------- ### Example Usage of Utility Types Source: https://github.com/didi/mpx/blob/master/docs-vitepress/articles/ts-derivation.md Demonstrates the practical application of StringKeyof and CombineStringKey with a sample object type. ```typescript const symbol1 = Symbol() type A = { 1: string a: string [symbol1]: string } type K = StringKeyof // 1 | 'a' type B = CombineStringKey<'', 'a'> // "a" type C = CombineStringKey // "a.b" type D = CombineStringKey // "a.b.c1" | "a.b.c2" type E = CombineStringKey // "a.b.c1.d" | "a.b.c2.d" ``` -------------------------------- ### MPX JSON Compiler Output Example Source: https://github.com/didi/mpx/blob/master/docs-vitepress/articles/mpx2.md This is an example of the text content generated by the json-compiler after processing a .mpx file. It formats the JSON data and prepares it for the next loader in the chain. ```javascript var json = { "usingComponents": { "list": "/components/list397512ea/list" } } module.exports = JSON.stringify(json, null, 2) ```