Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of using example of vue component Library

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

The main content of this article is "vue component library use example analysis", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "vue component library use example analysis" it!

Complete project directory structure

After git clone installs the dependency locally, execute npm run serve to develop the local component library and npm run docs:dev to develop the official website of the component library. Generally, after passing the test of a single component in src/demo.vue, it is introduced into .vuepress / components and put into the official website of the component library.

├─ docs / / vuepress development directory

│ ├─ .vuepress

│ │ ├─ components / / vue components that can be used in markdown

│ │ ├─ dist / / vuepress package directory

│ ├─ assets

│ ├─ css

│ ├─ img

│ └─ js

│ ├─ components

│ ├─ basic

│ ├─ form

│ ├─ navigation

│ ├─ notice

│ └─ other

│ └─ guide

│ │ │

│ │ ├─ config.js / / vurepess configuration modification entry, including left sidebar, upper right nav navigation menu, favicon, etc.

│ │ ├─ style.style / / overrides vuerpress default theme style

│ │ └─ public / / Common Resource Portal, such as favicon

│ ├─ static

│ │ ├─ img

│ │ └─ js

│ └─ views / / vuepress view file in markdown format

│ ├─ components

│ │ ├─ basic

│ │ ├─ form

│ │ ├─ navigation

│ │ ├─ notice

│ │ └─ other

│ ├─ design

│ │ └─ color

│ └─ guide

├─ src / / component library source code directory

│ ├─ button

│ ├─ cascader

│ ├─ collapse

│ ├─ container

│ ├─ datepicker

│ ├─ form

│ ├─ icon

│ ├─ layout

│ ├─ notice

│ ├─ plugins

│ ├─ slide

│ ├─ tab

│ ├─ step

│ ├─ sticky

│ └─ index.js / / component library source component entry file, execute the object file of npm run build

├─ package.json / / related to npm release, record version number, package entry file address

Learning component library will be rewarded.

Learn component packaging skills, good interface design, master component design routines

Tamp the foundation of js/css

In-depth understanding of vue

Production process

Component design / development

Publish npm

Make a display on the official website

Component design / development

Frequently involved vue api include

$children: gets the current component subcomponents.

Parent: gets the parent component of the current component.

Options: the initialization option for the current Vue instance, which you can use to get the name of the component.

Refs: an object that holds all DOM elements and component instances that have registered the ref feature.

El: the root DOM element used by the Vue instance.

Provide & inject: this pair of options need to be used together to allow an ancestral component to inject a dependency into all its descendants, not responsive. The injected object can be the eventBus of a vue instance.

On: the component listens for custom events.

Emit: the component triggers a custom event.

.sync: syntax sugar, in one-way data flow, after the parent component listens to the intention of the child component to modify the props, the parent component modifies the incoming props. The parent component does not need to explicitly trigger custom events within the parent component listener component to modify the value. The parent component only needs to write: X.sync = "bindValue". Note that the event triggered by the child component must be "update:x" before the syntax sugar takes effect.

The updated lifecycle hook function, which is re-rendered and patched by a virtual DOM due to data changes, is then called and may be used in parent-child component communication.

BeforeDestoryed/ destory lifecycle hook function, all event listeners of the component after destory will be removed. Note: if you add event listeners to the dom within the component, you need to manually contact the additional listeners you added when the component is destroyed. And the component is destroyed, and the dom element is still left on the page, which needs to be cleared manually. You can call native js api, node.remove () to clear the dom node.

Native js api includes:

Target.addEventListener (type, listener [, useCapture]) / removeEventListener since this is the basic content of the DOM2 specification, almost all browsers support this and do not require special cross-browser compatible code.

Node.contains () returns a Boolean value indicating whether the incoming node is a descendant of that node. It is often used for event monitoring to determine whether the target area has been clicked.

Window.scrollY gets the scrolling distance in the vertical direction of the document.

Element.getBoundingClientRect () returns the size of the element and its position relative to the viewport, and an object, including width/height/left/right/top/bottom. It is mostly used to calculate the location.

Summary of technical points

The idea of component design includes single data stream / eventBus event center, and the core is component communication.

Single data flow: the change of data is unidirectional, that is, through the way of props, only the parent component can modify the data, and the child component cannot actively modify the props. Such an example is in the collapse/tab/slide component, where the parent component controls the selected value. The idea of unidirectional data flow makes data modification better designed and the logic clearer.

Vue plug-in development: when to develop with plug-ins? When the component is not explicitly called in the code, it is not written directly in template, but is mounted into the document by calling methods on the Vue prototype chain.

Such as modal modal box / toast pop-up window. The basic idea of plug-in design is to expose an install method, which adds a custom method X to the vue prototype chain, introduces component an into X, obtains the component constructor Constructor through Vue.extend (a), obtains the component instance vm through new Constructor ({propsData}), and then mounts the component instance into the document.

Import modal from'.. / notice/modal'export default {install (vue, options) {const Construtor = vue.extend (modal) let modalVm / / ensure that there is only one modal instance globally let lastOption vue.prototype.$modal = (options) = > {if (lastOption! = = JSON.stringify (options)) {/ /! ModalVm modalVm = new Construtor ({propsData: options}) modalVm.$mount () document.body.append (modalVm.$el)} lastOption = JSON.stringify (options) modalVm.isVisible = true}

EventBus: when do I use eventBus? When a change in state requires multiple sub-components to be notified. For example, in the tab component, the selected value changes. Tab-head needs to perceive the change to make the short line of the prompt animate and slide under the selected tag. Tab-item needs to perceive the change to make the text become the selected style. Tab-pane needs to sense the change to make the selected panel appear.

Recursion: used in the design of cascade components. Similar to the function fn, use setTimout (fn,millseconds) to call yourself to achieve the recursive effect of setInterval. Components can call themselves recursively as long as the name property is provided internally. Allows the component template to call itself recursively. By providing the name option, it is easy to debug, and you can see component tags that can get more semantic information in the console.

Media query & flex layout: the principle of responsive layout is media query and percentage layout, and a class name takes effect when it is between a certain size; most layout-related ones use flex, which is very easy to use. Take a detailed look at teacher Ruan Yifeng's tutorial.

Component type component single data stream vue plug-in development eventBus native js operation dom & event recursive media query & flex layout basic button button-basic icon icon-basic grid grid-yes basic layout layout-yes form input input box-form cascader cascading selector yes---yes- form-form datepicker Date selector-yes-- navigation tab tab-- yes--- navigation step step adjustment-notify toast prompt-yes-yes-- notification popover pop-up box-yes-- notification modal mode box-yes-yes-- other collapse folding panel yes-yes--- other slide carousel graph yes- other sticky stickiness-

Three elements of component design

Props: you can refer to ele.me or antd. You need to consider how to use it easily and have good scalability from the user's point of view. Generally, you need to check the type and valid value and set the default value.

Slot: slot content distribution, using scope slots so that slot can also obtain component internal methods, so that user-defined content pages can call component internal methods. For example, in the popover pop-up box, the user wants to add a button to manually call off.

Event: component event. From the user's point of view, for example, in the datepicker component, the user wants to operate when the date panel is opened or closed. This is commonly used in interactive UI components.

For instance

Development idea of complex component datepicker

1. Develop on the original popover components

Click on an element A (input box) to pop up element B (date panel)

2. Generate date panel

Generate 7'6'42 dates, 6 lines to ensure that a month can be fully displayed on the panel. The most convenient way to calculate here is to use a timestamp to calculate the time stamp of the first day of the month and the day of the week, so that the 42 dates can be calculated at once. Do not count the last month and the next month is divided into three stages, such a problem is to consider the boundary situation, such as the occurrence of the previous year and the next year, and so on, trouble is easy to bug. These 42 dates are represented by visibleDays in computed.

VisibleDays () {let {year, month} = this.display let defaultObj = new Date (year, month, 28) var curMonthFirstDay = helper.getMonthFirstDay (defaultObj) var curMonthFirstDayDay = helper.getDay (curMonthFirstDay) = = 0? 7: helper.getDay (curMonthFirstDay) let x = curMonthFirstDayDay-1 / / how many bits var arr = [] for (let I = 0; I < 42; iTunes +) {arr.push (new Date (curMonthFirstDay.getTime () + (- x + I) * 3600 * 24 * 1000))} return arr}

3. Props accepts value with a type of date

When rendering the dates on the date panel, add a calculated class and add 'today','selected-date','available','prev-month','next-month',' respectively to distinguish between styles.

4. Realize the selected date

Tell the parent component to modify the data to allow the parent component to modify the incoming props, corresponding to the use of our component. The basic knowledge here is that the v-model on the component is a syntax sugar, and the vMube model = "x" will be parsed into: value= "a" @ input= "a=$event". At the same time, the data displayed in the input box on the panel also changes, so the calculation properties are used here, such as formattedValue in computed.

FormattedValue: {return this.value instanceof Date? Helper.getFormatDate (this.value):''}

5. Click previous year / month, next year / month

We need to know which year and month we are currently showing, and this data is maintained internally by the component, so declare a display object in data

Display: {year: (this.value & & this.value.getFullYear ()) | | new Date () .getFullYear (), month: (this.value & & this.value.getMonth ()) | | new Date () .getMonth ()}

When you click, modify the year/month of the display object. Because visibleDays is also a computational attribute and depends on the display object, click on the previous year / month and the next year / month, and the rendering date will also change.

6. Realize the selected year

The production of the year panel, generate 12 years, click on the first (12) year to render the upper (lower) 12 years. Here, you only need to bind events to the first and last dom elements of the rendered year, and the event listener passes in the value of the currently clicked element to calculate the previous or next 12 years.

Similarly, when you click on the year, use $emit to notify the parent component to modify the value

7. Realize the selected month

Write dead 12 months directly. Similarly, when you click on the month, use $emit to notify the parent component to modify the value.

8. Add buttons for [Today] and [empty] on the panel

When clicked, use $emit to notify the parent component to modify value,new Date () and''

9. Detail handling

Close the panel after the user has selected the date

After the user has selected the year, click on the date panel in the surrounding blank area to close, and the second click should display the day panel by default.

10. The user can modify the value in the input box to judge the validity.

If it is valid, $emit notifies the parent component to change the value, and if it is invalid, it will change back to the original value when it loses focus. Here, you need to use native js to modify the value for input. Note that it is not valid to change formattedValue directly here. Although the value of the input box is bound to: value= "formattedValue", because formattedValue is a calculation attribute and depends on this.value, this.value will not change if the user enters an invalid value, so the interface will not be updated, so you need to change the value of value manually.

SetValueManually ($event) {if (! helper.isValidDate ($event)) {this.$refs.inputWrapper.$refs.input.value = this.isDate (this.value)? Helper.getFormatDate (this.value):''return} this.$emit (' input', new Date ($event))}

11. Perfection

Add component custom events to the pop-up date panel and close date panel, that is, call $emit to trigger the 'showDatepicker'' and 'closeDatepicker' events.

Publish npm

1. Use the library mode of vue cli3 to package the code, modify the "build" in package.json: "vue-cli-service build-- target lib-- name sakura src/index.js", and output the umd build version after packaging, refer to vue cli.

What is umd? Unified module definition, can be compatible with common.js (node side specification) / AMD (browser side specification) / ES6 (node side does not fully support) and other modular solutions to ensure that the code can be run in a variety of environments.

File Size Gzippeddist/sakura.umd.min.js 13.28 kb 8.42 kbdist/sakura.umd.js 20.95 kb 10.22 kbdist/sakura.common.js 20.57 kb 10.09 kbdist/sakura.css 0.33 kb 0.23 kb

2. Specify the module entry "main": "dist/sakura.umd.min.js" in package.json

"name": "heian-sakura-ui", "version": "0.0.6", "private": false, "main": "dist/sakura.umd.min.js", "description": "an UI framework based on Vue.js"

3. Register a user on npm

4. Enter on the command line. Note that each release must modify the "version" in package.json: "0.0.x". "private" must be set to false before publishing.

Npm adduser / / prompt for registered user name npm publish

Official website production

Use vue press

1. Use in the original project

# installation relies on npm install-D vuepress# to create a docs directory mkdir docs

Script configuration in package.json

{"scripts": {"docs:dev": "vuepress dev docs", "docs:build": "vuepress build docs"}}

Then run npm run docs:dev to access

2. Simple configuration

Create a new file config.js under docs/.vuepress

Module.exports = {base:'/sakura-ui/', title: 'Sakura UI', description:' Inspiration from heian sakura', head: [['link', {rel:' icon', href:'/ favicon.ico'}]], themeConfig: {nav: [{text: 'Home', link:' /'}, {text: 'Github', link:' https://github.com/Firenzia/sakura-ui/'},] Sidebar: [{title: 'development guide', collapsable: true, children: ['views/guide/install.md',' views/guide/get-started.md']}, {title: 'design', collapsable: true, children: ['views/design/color/',]}, {title:' components', collapsable: true Children: ['views/components/basic/',' views/components/form/', 'views/components/navigation/',' views/components/notice/', 'views/components/other/']},]}

3. Use vue components

According to the official website, all * .vue files found in .vuepress / components will be automatically registered as global asynchronous components, which can be referenced in markdown, and the code in the vue file is highlighted. I use vue-highlightjs to view here.

4. Write documents

As all pages need to be rendered through the Node.js server when generating static HTML, for SSR-less friendly components (such as including custom instructions), you can wrap them in the built-in ClientOnly component, and note that because it is ssr, the component internal beforeCreate, created lifecycle hook function can not access the browser / DOM API, can only be called in beforeMount and mounted.

-title: 'Basic basis' sidebarDepth: 2 Icon Icon icon Attributes | Parameter | description | Type | optional value | default value | |:-| | name | Icon name | string |-| | color | Icon color, which supports common and hexadecimal colors | string |-|-|

5. Override the default theme style

Add style.styl to overwrite under .vuepress.

At this point, I believe that everyone on the "vue component library use example analysis" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report