### Install Project Dependencies Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/README.md This section provides commands to install project dependencies using npm. It includes a standard installation command and an alternative command using a different registry mirror to potentially speed up downloads or resolve issues with the default registry. ```bash npm i # Alternative installation with a mirror registry npm i --registry=https://registry.npmmirror.com ``` -------------------------------- ### Run Development Server Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/README.md This command starts the development server for the frontend project. It typically includes features like hot module replacement and automatically opens the application in the default web browser. ```bash npm run serve ``` -------------------------------- ### Install pit-element-ui Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/integrate.md Installs the pit-element-ui package using npm. This is the initial step for integrating the UI library. ```sh npm i pit-element-ui ``` -------------------------------- ### Install and Register pit-bimwin-ui Component Source: https://context7.com/yidianhengji/pit-common-doc/llms.txt Instructions for installing the pit-bimwin-ui library via npm and registering it as a Vue plugin in your main application file. This setup is required before using the BIM viewer component. ```sh # Install npm i pit-bimwin-ui ``` ```javascript // Register component in main.js import Vue from 'vue' import PitBimWinUi from 'pit-bimwin-ui' import 'pit-bimwin-ui/lib/PIT.css' Vue.use(PitBimWinUi) ``` -------------------------------- ### Basic vue.config.js Configuration (Vue.js) Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/vue/vueConfig.md This is a comprehensive `vue.config.js` example demonstrating common configurations. It includes setting the public path, configuring the dev server with proxy settings for API requests, and setting up webpack aliases for module resolution. It also shows how to configure SCSS preprocessing with variable imports. ```javascript const path = require('path') //引⼊path模块 function resolve(dir) { return path.join(__dirname, dir) //path.join(__dirname)设置绝对路径 } module.exports = { publicPath: './', devServer: { disableHostCheck: true, port: 8082, // open: true, proxy: { '/api': { // target: 'http://localhost:3002', target: 'http://www.baidu.com:45290', changeOrigin: true, pathRewrite: { '^/api': '/', }, }, '/info': { target: 'http://xinlang.com:9999', changeOrigin: true, pathRewrite: { '^/info': '/', }, }, }, }, chainWebpack: (config) => { config.resolve.alias .set('@', resolve('./src')) .set('components', resolve('./src/components')) .set('assets', resolve('./src/assets')) .set('common', resolve('./src/common')) .set('network', resolve('./src/network')) .set('views', resolve('./src/views')) //set第⼀个参数:设置的别名,第⼆个参数:设置的路径 }, css: { loaderOptions: { sass: { prependData: `@import "@/assets/scss/_variable.scss";`, }, }, }, } ``` -------------------------------- ### 在配置文件中指定插件环境 (JSON) Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md 当使用 ESLint 插件提供的环境时,需要在 `plugins` 数组中列出插件名,并在 `env` 配置中以 `plugin-name/environment-name` 的格式指定。例如,`"example/custom": true` 启用了 `example` 插件的 `custom` 环境。 ```json { "plugins": ["example"], "env": { "example/custom": true } } ``` -------------------------------- ### Build for Production Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/README.md This command is used to create a production-ready build of the frontend application. It usually involves optimizations like minification, code splitting, and asset bundling for deployment. ```bash npm run build ``` -------------------------------- ### EditorConfig Example Configuration Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/editorconfig.md A sample .editorconfig file demonstrating common configurations for various file types. This configuration ensures consistent coding styles such as character encoding, indentation, line endings, and whitespace handling across the project. ```editorconfig # http://editorconfig.org root = true # 对所有文件生效 [*] charset = utf-8 indent_style = space indent_size = 2 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true # 对后缀名为 md 的文件生效 [*.md] trim_trailing_whitespace = false ``` -------------------------------- ### Install pit-generator-ui Dependency Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/customerForm.md This command installs the necessary UI generator package for custom forms. It's a prerequisite for frontend integration. ```shell npm i pit-generator-ui ``` -------------------------------- ### Install ESLint and Prettier Dependencies Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md This JSON object lists the necessary npm packages to install for integrating ESLint and Prettier into a project. It includes core ESLint, Prettier, and related plugins for Vue and Babel. ```json { "eslint": "^7.32.0", "eslint-config-prettier": "^8.4.0", "eslint-plugin-vue": "^8.5.0", "eslint-plugin-prettier": "^4.0.0", "prettier": "^2.5.1", "@babel/core": "^7.17.5", "@babel/eslint-parser": "^7.5.4", "@babel/preset-env": "^7.16.11", "@babel/register": "^7.17.0" } ``` -------------------------------- ### ESLint Ignore File Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md An example of an `.eslintignore` file, which specifies patterns for files and directories that ESLint should ignore during analysis. This helps to exclude irrelevant or auto-generated files from linting. ```ignore build/*.js src/assets public dist src ``` -------------------------------- ### Install and Import pit-utils Source: https://context7.com/yidianhengji/pit-common-doc/llms.txt Instructions for installing the pit-utils JavaScript library using npm and how to import its functions into your project, either all at once or selectively. ```bash # 安装 npm i --save pit-utils # 在项目中引入 import * as pitUtils from 'pit-utils' # 单个函数引入 import { getType, chunk, camelCase } from 'pit-utils' ``` -------------------------------- ### Configure npm Registry Source with nrm Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/README.md This snippet demonstrates how to install and configure nrm to manage npm registry sources. It includes commands to add a custom 'pit' registry and set it as the default. This is useful for ensuring dependencies are fetched from a specific internal or private registry. ```bash # Install nrm npm install -g nrm # View available sources nrm ls # Add pit source nrm add pit http://172.18.3.46:4873/ # Set pit source as default nrm use pit ``` -------------------------------- ### CommonFormItem Constructor and Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/flutter/doc.md This snippet shows the constructor for the CommonFormItem widget in Dart, listing all its configurable parameters. It also includes a practical example demonstrating how to use the CommonFormItem with various options. ```dart const CommonFormItem({ super.key, this.isInput = false, this.controller, this.leftFontSize, this.rightFontSize, this.rightTextSize, this.hintTextSize, this.perCent = 0.5, this.padding = 10, this.isRequired = true, this.isRightWidget = true, this.isHintText = true, this.isRightImage = true, this.bottomBorder = true, this.obscureText = false, this.focusNode, this.isBottomBorder = false, this.hintText = '请输入', this.rightWidget, this.onTap, required this.leftText, this.rightText, this.rightTextColor = Colors.grey, this.leftTextColor = Colors.black, this.bgColor = Colors.white, this.onChanged, this.contentPadding = const EdgeInsets.fromLTRB(0, 0, 7, 0), this.textFieldPadding = const EdgeInsets.fromLTRB(0, 0, 12, 0), this.keyboardType = TextInputType.multiline, this.inputFormatters, this.maxLines = 1, this.rightWidth, this.enabled, }); //示例 CommonFormItem( key: Key('form_item_key'), isInput: true, controller: TextEditingController(), leftFontSize: 16, rightFontSize: 14, hintTextSize: 12, perCent: 0.6, padding: 15, isRequired: true, isRightWidget: true, isHintText: true, isRightImage: true, bottomBorder: true, obscureText: false, focusNode: FocusNode(), isBottomBorder: false, hintText: '请输入内容', rightWidget: Icon(Icons.search), onTap: () { // 点击事件处理逻辑 }, leftText: '左侧文本', rightText: '右侧文本', rightTextColor: Colors.blue, leftTextColor: Colors.red, bgColor: Colors.yellow, onChanged: (text) { // 输入框内容变化事件处理逻辑 }, contentPadding: const EdgeInsets.fromLTRB(0, 0, 10, 0), textFieldPadding: const EdgeInsets.fromLTRB(0, 0, 15, 0), keyboardType: TextInputType.text, inputFormatters: [ FilteringTextInputFormatter.digitsOnly, ], maxLines: 3, rightWidth: 80, enabled: true, ) ``` -------------------------------- ### Install pit-gis using npm Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/pitGis/README.md This command installs the pit-gis library as a project dependency using npm. It's the first step to integrate the library into your project. ```sh npm i --save pit-gis ``` -------------------------------- ### Import pit-gis in JavaScript Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/pitGis/README.md This JavaScript code demonstrates how to import the pit-gis library into your project after installation. This import statement makes the library's functionalities available for use. ```js import * as pitGis from 'pit-gis' ``` -------------------------------- ### Install and Configure pit-element-ui Source: https://context7.com/yidianhengji/pit-common-doc/llms.txt Instructions for installing and configuring the pit-element-ui component library, a customized version of Element UI. It covers npm installation and global Vue configuration, including setting component sizes, internationalization, and custom theme properties. ```sh # 安装 npm i pit-element-ui ``` ```javascript // main.js 配置 import Vue from 'vue' import Element from 'pit-element-ui' import i18n from './i18n' Vue.use(Element, { size: 'small', // 默认组件尺寸 i18n: (key, value) => i18n.t(key, value), tableHeadBackground: '#f5f7fa', // 表格头部背景色 isHiddenEditBtn: 'hide', // 隐藏编辑按钮 isHiddenDelBtn: 'hide', // 隐藏删除按钮 dialogTop: '8vh', // 弹窗距顶部距离 paginationTotal: 'pagination.total' // 分页总数国际化 key }) // 配置请求方法 import request from '@/utils/request' Vue.prototype.request = request Vue.prototype.isOk = 200 Vue.prototype.dialogHeaderClass = 'dialog-header-class' ``` -------------------------------- ### initial Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/pitUtils/pitUtilsArray.md Gets the initial elements of `array`. ```APIDOC ## initial(array) ### Description Gets the initial elements of `array`. ### Method N/A (Utility Function) ### Endpoint N/A (Utility Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Description | |---|---|---| | array | Array | The array to query. | ### Return Value (Array): Returns the sliced array. ### Request Example ```javascript pitUtils.initial([1, 2, 3]) // => [1, 2] ``` ### Response #### Success Response (200) (Array): The sliced array. #### Response Example ```json [ 1, 2 ] ``` ``` -------------------------------- ### Vue Global Component Registration Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/vue/README.md Shows how to register Vue components globally. The first example registers components individually. The second example demonstrates using `require.context` to automatically import and register all components within a directory, simplifying the process when new components are added. ```javascript // import WmsTable from './wms-table/table/index'; import Table from './table/index.vue' import CustomHooks from './custom-hooks/custom-hooks-actions/index' import SFilter from './s-filter/filter-form' import WButton from './button/index' import CreateForm from './createForm/create-form/CreateForm.vue' import Action from './table/action-table-column.vue' import DetailItem from './detail-item.vue' Vue.component('w-filter', SFilter) Vue.component('w-button', WButton) Vue.component('custom-hooks', CustomHooks) Vue.component('create-form', CreateForm) Vue.component('w-table', Table) Vue.component('w-table-action', Action) Vue.component('zonetime-date-picker', ZonetimeDatePicker) Vue.component('detail', DetailItem) ``` ```javascript const contexts = require.context('./', true, /\.(vue|ts)$/) export default { install(vm) { contexts.keys().forEach((component) => { const componentEntity = contexts(component).default if (componentEntity.name) { vm.component(componentEntity.name, componentEntity) } }) }, } ``` -------------------------------- ### Flutter JhContactsTreePickerView Constructor and Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/flutter/doc.md Defines the constructor for the JhContactsTreePickerView Flutter widget, outlining its parameters for data, selection modes, and callbacks. Includes a practical example demonstrating its usage with sample data and configuration. ```dart const JhContactsTreePickerView({ super.key, required this.data, this.labelKey = _labelKey, this.valueKey = _valueKey, this.childrenKey = _childrenKey, this.title = _titleText, this.tabText = _tabText, this.values = const [], this.valuesKey = _valueKey, this.isShowSearch = true, this.searchHintText = _searchHintText, this.splitString = _splitString, this.isMultipleChoice = _isMultipleChoice, required this.clickCallBack, }); //示例 JhContactsTreePickerView( data: treeData, labelKey: 'name', valueKey: 'id', childrenKey: 'children', title: '选择联系人', tabText: '联系人', values: [1, 2], valuesKey: 'id', isShowSearch: true, searchHintText: '搜索联系人', splitString: ' > ', isMultipleChoice: true, clickCallBack: (selectedItems) { // 处理选择结果 }, ); ``` -------------------------------- ### pit-dialog Modal Component Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/component.md Example of using the pit-dialog component to create a modal with a title, visibility control, and close/confirm actions. It utilizes slots for footer content and demonstrates basic data binding and method handling. ```html ``` -------------------------------- ### Modify Request Utility for GET requests Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/integrate.md Adjusts the request utility in `src/utils/request.js` to handle GET requests by assigning data to params if params are not already present. This ensures consistent data handling for GET requests. ```js // 修改 if (config.method == 'get') { config.params = config.params ? config.params : config.data } ``` -------------------------------- ### Configure ServiceAgent for File Info and List Queries Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/pitBimWinUi/pitBimWinUi.md This section explains how to configure the ServiceAgent to handle file information and file list queries. It details the structure for 'fileInfoUri' and 'fileListUri', including 'url' and an 'intercept' function to adapt data to bimwin's requirements. The example shows how to set up these agents with specific API endpoints and data transformation logic. ```javascript options: { fileId: ["93d0f57ccc0140c99835e0af35850e90"], url: "http://172.18.1.72:9983/", // 具体字段url以后端人员协商为准, 以下为示例 agent: { fileInfo: { url: "api/convert/transfer-task/info/", intercept(res) { const { data } = res; return { extra: data.results, fileName: data.transferFileName, }; }, }, fileList: { url: "api/convert/transfer/transferList/", intercept(res) { return { code: 200, data: res.data.map((v) => ({ fileId: v.id, fileName: v.transferFileName, fileSize: Number(v.transferFileSize), fileUrl: v.transferFileUrl, fileType: v.transferFileType, })), }; }, }, } } ``` -------------------------------- ### Pad string from the start with specified characters and length Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/pitUtils/pitUtilsString.md The padStart function pads the given string on the left side if its length is less than the specified length. If the string exceeds the specified length, the excess part is truncated. It takes the string, the target length, and the padding characters as input. ```javascript pitUtils.padStart('abc', 6) // => ' abc' pitUtils.padStart('abc', 6, '_-') // => '_-_abc' pitUtils.padStart('abc', 3) // => 'abc' ``` -------------------------------- ### Prettier Ignore File Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md An example of a `.prettierignore` file, used to specify files and directories that Prettier should ignore when formatting code. This prevents Prettier from modifying files that should not be formatted. ```ignore node_modules docs/.vuepress/.cache docs/.vuepress/dist ``` -------------------------------- ### Open File Preview and Download Methods Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/component.md Provides global methods for file preview and download. Requires router instance configuration and proxy setup. Supports various download methods including by fileId, zip, blob, URL, and export metadata. ```javascript this.$openFilePreview(fileId) this.$downloadFile(fileId) this.$downloadZip(fileId) this.$downloadBlob(blob) this.$downloadUrl(url) this.$exportMeted({ data: Blob, headers: responseHeaders }) this.$openBaseImport(options) ``` -------------------------------- ### ESLint Rule: consistent-return Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md Shows an example violating the ESLint rule 'consistent-return'. This rule ensures that all return paths in a function yield values of the same type, preventing confusion. ```javascript function doSomething(condition) { if (condition) { return true } else { return // 隐式返回undefind, 如果使用===判断布尔值会为错误返回 } } ``` -------------------------------- ### Configure Vuex Store with Mutations Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/vue/vuexConfig.md Initializes a Vuex store and registers mutations. This example shows how to import mutations from a separate file and include them in the store configuration. ```javascript import mutations from './mutaions_type' export default new Vuex.Store({ mutations, }) ``` -------------------------------- ### ESLint Rule: complexity Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md Demonstrates the ESLint rule 'complexity', which enforces a maximum cyclomatic complexity for functions. The example function has multiple conditional paths, increasing its complexity. ```javascript function a(x) { if (true) { return x // 1st path } else if (false) { return x + 1 // 2nd path } else { return 4 // 3rd path } } ``` -------------------------------- ### String.prototype.padStart() and padEnd() Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/html/README.md padStart() and padEnd() methods pad the current string with another string (repeated, if needed) until the resulting string reaches the given length. Padding is applied from the start (left) or end (right) respectively. If the target length is less than the string's current length, the string is returned unchanged. ```javascript 'abc'.padStart(10) // " abc" 'abc'.padStart(10, 'foo') // "foofoofabc" 'abc'.padStart(6, '123465') // "123abc" 'abc'.padStart(8, '0') // "00000abc" 'abc'.padStart(1) // "abc" 'abc'.padEnd(10) // "abc " 'abc'.padEnd(10, 'foo') // "abcfoofoof" 'abc'.padEnd(6, '123456') // "abc123" 'abc'.padEnd(1) // "abc" ``` -------------------------------- ### ESLint Rule: prefer-const Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md Illustrates the ESLint rule 'prefer-const', which encourages the use of 'const' for variables that are not reassigned. The example shows the correct usage with 'const' and the incorrect usage with 'let'. ```javascript // 正确的 const a = '' // 错误的 let a = '' ``` -------------------------------- ### 在 package.json 中指定 ESLint 环境 Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md 在 `package.json` 文件中使用 `eslintConfig.env` 来配置 ESLint 的运行环境。这允许你在项目的主配置文件中集中管理 ESLint 设置。例如,启用 `browser` 和 `node` 环境。 ```json { "name": "mypackage", "version": "0.0.1", "eslintConfig": { "env": { "browser": true, "node": true } } } ``` -------------------------------- ### 在 Vue 项目中集成 pit-bimwim-ui Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/pitBimWinUi/README.md 在 Vue 项目的 main.js 文件中导入并使用 pit-bimwim-ui 组件。这包括导入 Vue、pit-bimwim-ui 库本身以及相关的 CSS 文件,然后通过 Vue.use() 方法进行全局注册。 ```javascript import Vue from 'vue' import PitBimWinUi from 'pit-bimwim-ui' import 'pit-bimwim-ui/lib/PIT.css' Vue.use(PitBimWinUi) ``` -------------------------------- ### ESLint Rule: no-unmodified-loop-condition Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md Shows an example that violates the ESLint rule 'no-unmodified-loop-condition'. This rule flags loops where the condition variable is not modified within the loop body, potentially indicating an infinite loop or a logic error. ```javascript var node = something while (node) { doSomething(node) } ``` -------------------------------- ### ESLint Rule: no-self-compare Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md Demonstrates the ESLint rule 'no-self-compare', which flags instances where a variable is compared to itself. This is often a sign of a bug or typo. ```javascript var x = 10 if (x === x) { x = 20 } ``` -------------------------------- ### Language Pack Structure Example (JavaScript) Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/i18n.md This JavaScript object demonstrates the structure of a language pack, including keys for routing, navigation, login, tags view, settings, common elements, components, request-related text, and specific business modules. It follows a nested object structure for organization. ```javascript export default { route: {}, // 路由标题 navbar: {}, // 导航栏 login: {}, // 登录页 tagsView: {}, // 标签页 settings: {}, // 设置 common: {}, // 通用文本 components: {}, // 组件文本 requestCommon: {}, // 请求相关 loginCommon: {}, // 登录页相关 ganttCommon: {}, // Gantt图相关 modules: {}, // 业务模块相关文本 "xxxxx模块": {}, // 具体业务模块... // 其他模块... } ``` -------------------------------- ### Get Geographic Timezone Utility Function Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/i18n.md A JavaScript utility function that retrieves the current geographic timezone of the user. It returns the timezone as a string, for example, 'Asia/Shanghai'. This function has no parameters. ```javascript import { getGeographicTimezone } from '@/utils/constant' const timezone = getGeographicTimezone() // 'Asia/Shanghai' ``` -------------------------------- ### Importing THREE from pitBimwinUi (JavaScript) Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/pitBimWinUi/pitBimWinUi.md Shows how to import the THREE library from the pitBimwinUi module, which is necessary for using THREE.Matrix4 and other THREE-related functionalities. ```javascript import ui from 'pit-bimwin-ui' const THREE = ui.THREE ``` -------------------------------- ### pit-bim-win-ui Component Usage and Configuration Source: https://context7.com/yidianhengji/pit-common-doc/llms.txt Example of using the main pit-bim-win-ui component in a Vue template. It shows how to pass configuration options, headers for authentication, and control the visible toolbar items. Event handlers for model loading and point picking are also demonstrated. ```vue ``` -------------------------------- ### ESLint Rule: no-use-before-define Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md Illustrates the ESLint rule 'no-use-before-define', which prohibits using a variable before it has been declared. This helps prevent common JavaScript errors related to variable hoisting. ```javascript alert(a) var a = 10 ``` -------------------------------- ### ESLint Rule: require-await Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md Demonstrates a violation of the ESLint rule 'require-await'. This rule mandates that asynchronous functions must contain an 'await' expression, ensuring that asynchronous operations are properly handled. ```javascript // 错误的 async function foo() { doSomething() } ``` -------------------------------- ### Get Platform Instance Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/pitBimWinUi/pitBimWinUi.md Retrieves the BIM viewer platform instance. ```APIDOC ## GET /api/platform ### Description Retrieves the BIM viewer platform instance. ### Method GET ### Endpoint /api/platform ### Parameters None ### Response #### Success Response (200) - **platform** (object) - The BIM viewer platform instance. #### Response Example ```json { "platform": "[Platform Instance Object]" } ``` ``` -------------------------------- ### ESLint Rule: no-inline-comments Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md Contrasts incorrect and correct usage of inline comments according to the ESLint rule 'no-inline-comments'. This rule discourages comments placed on the same line as code, promoting better readability. ```javascript // 错误的 data() { return { data: [], // 树数据 } }, ``` ```javascript // 正确的 data() { return { // 树数据 data: [], } }, ``` -------------------------------- ### Vue Plugin Registration with Vue.use Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/vue/README.md Demonstrates how to register multiple components from a library (like Vant) as a Vue plugin. This approach centralizes component registration, making the main application file cleaner. It requires importing the components and defining an install function. ```javascript import { Toast, Button } from 'vant' const components = { Toast, Button, } const componentsHandler = { install(Vue) { Object.keys(components).forEach((key) => Vue.use(components[key])) } } export default componentsHandler ``` ```javascript import Vue from 'vue' import vantCompoents from '@/config/vant.config' Vue.config.productionTip = false Vue.use(vantCompoents) new Vue({ render: (h) => h(App), }).$mount('#app') ``` -------------------------------- ### Class Definition and Instantiation (JavaScript) Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/html/html.md Shows how to define a class in JavaScript using ES6 syntax. It includes a constructor for initializing object properties and methods to define object behavior. Examples demonstrate creating instances of the class and calling its methods. ```javascript class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hello, 我叫${this.name},年龄${this.age}`); } } // 创建类的实例 const person1 = new Person('张三', 20); const person2 = new Person('李四', 22); // 类的方法 person1.greet(); // Hello, 我叫张三,年龄20 person2.greet(); // Hello, 我叫李四,年龄22 ``` -------------------------------- ### ESLint Rule: no-template-curly-in-string Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md Illustrates the ESLint rule 'no-template-curly-in-string', which prevents the use of template literal placeholder syntax within regular strings. This avoids potential confusion with actual template literals. ```javascript 'Hello ${name}!' 'Hello ${name}!' 'Time: ${12 * 60 * 60 * 1000}' ``` -------------------------------- ### Configure Development API URL Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/README.md This snippet shows how to configure the API endpoint for the development environment. It involves modifying a JavaScript file (`src/utils/define.js`) and setting a constant variable `APIURl` to the desired development server address. ```javascript // Development environment API configuration const APIURl = 'http://192.168.0.10:7772' ``` -------------------------------- ### Register Custom Form Components in Vue Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/customerForm.md This JavaScript code registers various custom form components with Vue. Ensure all required components are imported and registered to be available in your application. This is part of the frontend setup. ```javascript // 自定义表单组件 import pitText from './pit-generator/components/pit-text.vue' import pitAddress from './pit-generator/components/pit-address.vue' import pitGroupTitle from './pit-generator/components/pit-group-title.vue' import pitInputTable from './pit-generator/components/pit-input-table.vue' import pitPopupSelect from './pit-generator/components/pit-popup-select.vue' import pitUploadTable2 from './pit-generator/components/pit-upload-table-item.vue' import pitRelationForm from './pit-generator/components/pit-relation-form.vue' export default { install(Vue) { // 自定义表单用 Vue.component('pit-text', pitText) Vue.component('pit-address', pitAddress) Vue.component('pit-group-title', pitGroupTitle) Vue.component('pit-input-table', pitInputTable) Vue.component('pit-popup-select', pitPopupSelect) Vue.component('pit-transfer-tree', pitTransferTree) Vue.component('pit-upload-table2', pitUploadTable2) Vue.component('pit-relation-form', pitRelationForm) }, } ``` -------------------------------- ### CommonSelectView Constructor and Usage Examples (Dart) Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/flutter/doc.md This snippet details the constructor for the CommonSelectView widget in Dart, outlining its various parameters for customization. It also provides multiple usage examples demonstrating different functionalities like handling options lists, enabling editing with input formatters, displaying static text, configuring fixed widths, and highlighting required fields with custom text colors. ```dart const CommonSelectView( {Key? key, this.leftText, this.rightText, this.hintText, this.rightTextList, this.onTap, this.textEditingController, this.onChanged, this.isDelete = false, this.isEdit = false, this.isRequired = false, this.isRightTextColor = false, this.margin = const EdgeInsets.only(right: 10), this.inputFormatters, this.idList, this.width = 130, this.customKeyWidth = 900 }) // 基础用法 // 带选项列表和删除按钮 List options = ['北京', '上海', '广州']; List cityIds = [110000, 310000, 440100]; CommonSelectView( leftText: "所在城市", rightTextList: options, idList: cityIds, isDelete: true, onTap: () { showModalBottomSheet( context: context, builder: (_) => CityPicker(/* 城市选择器实现 */) ).then((selectedId) { if(selectedId != null) { final index = cityIds.indexOf(selectedId); setState(() => currentCity = options[index]); } }); }, ) // 可编辑的输入框(带格式限制) final _controller = TextEditingController(); CommonSelectView( leftText: "手机号码", isEdit: true, hintText: "请输入11位手机号", textEditingController: _controller, inputFormatters: [ FilteringTextInputFormatter.digitsOnly, LengthLimitingTextInputFormatter(11) ], onChanged: (value) => print("输入内容:$value"), ) // 显示静态文本(非编辑模式) CommonSelectView( leftText: "用户姓名", rightText: "张三", isRequired: true, margin: EdgeInsets.only(right: 15), ) // 固定宽度布局 CommonSelectView( leftText: "详细地址", width: 200, customKeyWidth: 80, isEdit: true, hintText: "街道门牌号", ) // 带必填标识和主题色强调 CommonSelectView( leftText: "订单类型", isRequired: true, isRightTextColor: true, rightText: "普通订单", onTap: () => _showOrderTypePicker(), ) ``` -------------------------------- ### Sequential Asynchronous Steps with Async/Await Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/html/async.md Presents the same multi-step asynchronous process as the previous example, but implemented using `async` and `await` for improved readability and a synchronous code style. ```javascript function takeLongTime(n) { return new Promise((resolve) => { setTimeout(() => resolve(n + 200), n) }) } function step1(n) { console.log(`step1 with ${n}`) return takeLongTime(n) } function step2(n) { console.log(`step2 with ${n}`) return takeLongTime(n) } function step3(n) { console.log(`step3 with ${n}`) return takeLongTime(n) } async function doIt() { console.time('doIt') const time1 = 300 const time2 = await step1(time1) const time3 = await step2(time2) const result = await step3(time3) console.log(`result is ${result}`) console.timeEnd('doIt') } doIt() ``` -------------------------------- ### Remove Console Logs in Production (Babel Configuration) Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/vue/vueConfig.md This configuration for `babel.config.js` uses the `babel-plugin-transform-remove-console` plugin to automatically remove `console.log` statements from the production build. It allows retaining `console.error` and `console.warn` messages. Install the plugin as a dev dependency. ```javascript // 所有⽣产环境 const prodPlugin = [] if (process.env.NODE_ENV === 'production') { // 如果是⽣产环境,则⾃动清理掉打印的⽇志,但保留error 与 warn prodPlugin.push([ 'transform-remove-console', { // 保留 console.error 与 console.warn exclude: ['error', 'warn'], }, ]) } module.exports = { plugins: [...prodPlugin], } // 或者: // config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true ``` -------------------------------- ### Include CesiumJS dependencies for initialization Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/pitGis/README.md These HTML lines show how to include the necessary CesiumJS CSS and JavaScript files in your project's index file. These are required for initializing the GIS map using pit-gis. ```html ``` -------------------------------- ### ESLint Rule: no-unreachable-loop Example Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md This code snippet demonstrates a scenario that triggers the ESLint rule 'no-unreachable-loop'. It highlights a loop whose body is structured in a way that it can only execute once, suggesting a potential logical error, such as a missing 'break' statement. ```javascript for (let i = 0; i < arr.length; i++) { if (arr[i].name === myName) { doSomething(arr[i]) // break was supposed to be here } break } ``` -------------------------------- ### Enable Compression with compression-webpack-plugin (Vue.js) Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/vue/vueConfig.md This snippet demonstrates how to configure `compression-webpack-plugin` in `vue.config.js` to enable Gzip compression for JavaScript, HTML, and CSS files in production builds. It helps reduce file sizes and improve page load times. Ensure `compression-webpack-plugin` is installed as a dev dependency. ```javascript const CompressionWebpackPlugin = require('compression-webpackplugin') const isProd = process.env.NODE_ENV === 'production' module.exports = { configureWebpack: (config) => { if (isProd) { // 配置webpack 压缩 config.plugins.push( new CompressionWebpackPlugin({ test: /\.js$|\.html$|\.css$/, // 超过4kb压缩 threshold: 4096, }) ) } }, } ``` -------------------------------- ### 在 YAML 配置文件中指定 ESLint 环境 Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/standard/README.md 在 YAML 格式的 ESLint 配置文件中使用 `env` 关键字来启用环境。这提供了一种更简洁的配置语法。例如,`browser: true` 和 `node: true` 会启用这两个环境。 ```yaml --- env: browser: true node: true ``` -------------------------------- ### take Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/pitUtils/pitUtilsArray.md Creates a slice of an array, taking the first `n` elements. ```APIDOC ## take(array, [n=1]) ### Description Creates a slice of `array` with `n` elements taken from the beginning. ### Method `take` ### Parameters #### Path Parameters - **array** (Array) - The array to query. - **[n=1]** (number) - The number of elements to take. ### Response #### Success Response (Array) - **slicedArray** (Array) - Returns the slice of `array`. ### Request Example ```js pitUtils.take([1, 2, 3]) // => [1] pitUtils.take([1, 2, 3], 2) // => [1, 2] pitUtils.take([1, 2, 3], 5) // => [1, 2, 3] pitUtils.take([1, 2, 3], 0) // => [] ``` ``` -------------------------------- ### Integrate vConsole for Mobile Debugging (Vue.js) Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/vue/vueConfig.md This code snippet shows how to conditionally import and initialize `vConsole` in the `main.js` file. It ensures that the vConsole debugging tool is only active during development, providing an in-app console for mobile debugging without affecting production builds. Install `vConsole` as a dependency. ```javascript // 开发环境下⾯使⽤vConsole进⾏调试 if (process.env.NODE_ENV === 'development') { const VConsole = require('vconsole') new VConsole() } ``` -------------------------------- ### Configure Mobile Adaptation with postcss-px-to-viewport (Vue.js) Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/vue/vueConfig.md This configuration sets up `postcss-px-to-viewport` to automatically convert pixel units to viewport units (vw) for mobile responsiveness. It's defined in `postcss.config.js` and allows customization of viewport width, unit precision, and blacklisted selectors. Install `postcss-px-to-viewport` as a dev dependency. ```javascript module.exports = { plugins: { autoprefixer: {}, 'postcss-px-to-viewport': { // 视窗的宽度,对应的是我们设计稿的宽度,我们公司⽤的是375 viewportWidth: 375, // 视窗的⾼度,根据750设备的宽度来指定,⼀般指定1334,也可以不配置 // viewportHeight: 1334, // 指定`px`转换为视窗单位值的⼩数位数 unitPrecision: 3, // 指定需要转换成的视窗单位,建议使⽤vw viewportUnit: 'vw', // 指定不转换为视窗单位的类,可以⾃定义,可以⽆限添加,建议定义⼀⾄两个通⽤的类名 selectorBlackList: ['.ignore'], // ⼩于或等于`1px`不转换为视窗单位,你也可以设置为你想要的值 minPixelValue: 1, // 允许在媒体查询中转换`px` mediaQuery: false, }, }, } ``` -------------------------------- ### Run Code Quality Checks Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/jnpfFrame/README.md This section provides commands for maintaining code quality. 'npm run lint' typically runs a linter (like ESLint) to check for code style and potential errors, while 'npm run prettier' formats the code according to predefined style rules. ```bash # Code format check npm run lint # Code format npm run prettier ``` -------------------------------- ### Custom Request Headers (JavaScript) Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/pitBimWinUi/pitBimWinUi.md Example of custom request headers that can be passed. This includes standard headers like 'token' and 'Authorization', as well as arbitrary custom headers. ```javascript headers: { token: "0e8d286ecfa84f01a97c7733b8aeb4a2dt3xrlvrghl", loginMark: "6Iqx6Ze05LiA5aO26YWS77yM54us6YWM5peg55u45Lqy", Authorization: "hello world", ssssssssssssss: "i can custom request headers!" } ``` -------------------------------- ### Basic Asynchronous Operation with Async/Await Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/html/async.md Shows the equivalent of the Promise-based example using `async` and `await` keywords for a more synchronous-looking code structure. ```javascript function takeLongTime() { return new Promise((resolve) => { setTimeout(() => resolve('long_time_value'), 1000) }) } async function test() { const v = await takeLongTime() console.log(v) } test() ``` -------------------------------- ### Get Last Element of Array Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/pitUtils/pitUtilsArray.md Gets the last element of the array. ```javascript pitUtils.last([1, 2, 3]) // => 3 ``` -------------------------------- ### Displaying a pit-bim-win-dialog Modal (HTML) Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/pitBimWinUi/PitBimWinDialog.md This snippet demonstrates how to use the pit-bim-win-dialog component in HTML. It shows how to control visibility, set a title, define dimensions and position, and attach a close callback function. It also includes an example of content within the dialog, such as a button that interacts with a 'bimWin' function. ```html ``` -------------------------------- ### Vue $watch: Dynamic and Cancellable Data Observation Source: https://github.com/yidianhengji/pit-common-doc/blob/main/docs/vue/README.md This JavaScript example illustrates the use of `$watch` in Vue.js for dynamic and on-demand data observation. It shows how to start watching a property (`formData`) after initial data loading and how to cancel the watcher using the returned `unwatch` function. This is particularly useful for editing forms where initial data population shouldn't trigger the 'dirty' state, but subsequent user changes should. ```javascript export default { data() { return { formData: { name: '', age: 0, }, } }, created() { this.$_loadData() }, methods: { // Simulate asynchronous data request $_loadData() { setTimeout(() => { // Assign first this.formData = { name: 'Zi Jun', age: 18, } // After form data is filled, listen for data changes const unwatch = this.$watch( 'formData', () => { console.log('Data has changed') }, { deep: true } ) // Simulate data change setTimeout(() => { this.formData.name = 'Zhang San' }, 1000) }, 1000) }, }, } ```