Detailed explanation of abstract Vue public components
This article mainly introduces how to abstract a Vue public component. Taking a numeric keyboard component as an example, it has certain reference value. Interested friends can refer to it. I hope it can help everyone.
I have always wanted to write an essay about abstract Vue components, but I have never thought of a good example. It happened that I recently made a numeric keyboard component for a company project, so I used this as an example to talk about how to abstract Vue components.
First upload the Demo and source code. (The demo is best viewed in mobile browser mode)
Before talking about the specific implementation, I would like to share what I think the ideal public component looks like:
1. Black box, that is, other developers besides yourself can get started immediately after quickly reading the usage documentation, without caring about your internal implementation;
2. Independence, that is, decoupling, no There are too many connections with the parent component;
3 Customization, appropriately expose some input interfaces or methods to the outside for customization, and also set the default values of these properties when they are not input externally.
Let’s first use a black box to see how the numeric keyboard component in the demo is called (non-critical parts of the code have been omitted).
App.vue
<template> ...... <keyboard></keyboard> </template> <script> import keyboard from 'Keyboard.vue'; export default { data() { return { value: '' }; }, methods: { handleChange(value, currentValue) { console.log(value, currentValue); this.value = value; }, handleSubmit() { console.log('submit: ' + this.value); } } } </script>
As above, the most basic call is completed. The effect is as follows:
#Then, click 1-6 and "OK". If it is as follows:
#You can see that the numeric keyboard has worked as expected. Next, analyze all the input items of the numeric keyboard component.
@change-event: This event is a custom event. The parent component registers for listening through v-on, and the child component is triggered internally through $emit (for more information about custom events, please refer to: Vue official tutorial) .
This event will be triggered every time you click the numeric keys and the backspace key, which passes two parameters: value, the accumulated clicked character combination; currentValue, the currently clicked character. The parent component receives the callback content of this event through the handleChange method.
@submit-event: This event will be triggered when the "OK" button is clicked. It does not pass parameters and just tells the parent component "My OK button was clicked. It is up to you what you want to do." Well, the number clicked previously has been passed to you through change-event." The parent component receives the callback through the handleSubmit method.
It would be too insincere to only write these two methods. I also wrote the following custom attributes based on some scenarios.
max: Maximum input length. The excess length will not trigger the change-event event. There is no limit by default.
<keyboard></keyboard>
sp-key: Customized special characters, such as "X" when entering the ID card, will be added to the blank space in the lower left corner, default is none.
<keyboard></keyboard>
random: Whether to disrupt the order of numbers. This is often seen when entering bank accounts or passwords. The default is false.
<keyboard></keyboard>
From the above custom properties and events, we roughly know how the parent component passes values to the child components and monitors changes in the child components, but the parent component How to directly call the function inside the subcomponent? Let's look at the following scene.
The keyboard icon on the numeric keyboard will hide the numeric keyboard when clicked. There is a method keyboardToggle(true|false) inside the component to control the pop-up and retraction of the keyboard. So what if you also want to call this method outside the component? For example, when the input in the parent component gets focus.
You can obtain the component reference of the keyboard through the ref attribute in Vue to call its internal methods, as follows:
$refs.[refName].keyboardToggle(true|false)
<keyboard></keyboard> <script> import keyboard from 'Keyboard'; export default { //... methods: { handleShowKeyboard(e) { e && e.preventDefault(); this.$refs.kbref.keyboardToggle(true); } } } </script>
In the above form, you can call methods in the child component in the context of the parent component.
$refs.[refName].handleInit()
Initialization method inside the numeric keyboard component, used to re-render the component. If the random property is true, the numeric keys will refresh the random arrangement.
$refs.[refName].handleClear()
Clear the previously entered character combination, trigger change-event and return an empty string.
All the external properties and events of this component are shared above. It can be found that we have not seen a line of code inside the component, but we can already use it completely. Let’s talk about the internal implementation.
First let’s take a look at the layout. I divided the keyboard into left and right parts. Needless to say, the right part is a key bit array generated through a v-for loop.
So how to make a space between 0 and 9 empty? Let’s take a look at the method of initializing the keyboard component.
keyboard.vue
handleInit()
<template> <p> </p> <p> </p> <p>{{item}}</p> <p></p> //键盘图标 <p> //... </p> </template> <script> export default { data() { return { baseArr: [] } }, computed: { keyArr() { this.handleInit(); return this.baseArr; } }, methods: { handleInit() { this.baseArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']; this.baseArr.splice(this.baseArr.length - 1, 0, ''); } } } </script>
That is, insert a null character in the second to last position of the key array, and then generate keys in a loop. Let’s take a look at how custom parameters take effect.
sp-key
<script> export default { props: ['spKey'], data() { return { baseArr: [] } }, //.... methods: { handleInit() { let spKey = this.spKey; this.baseArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']; this.baseArr.splice(this.baseArr.length - 1, 0, spKey); } } } </script>
在组件内部通过 props 属性接收父组件传递的 spKey,之后就可在组件内的属性和方法中通过 this.spKey 进行访问。首先判断 spKey 值是否有效,并代替空字符插入键位数组倒数第二项。
random
<script> export default { props: ['spKey', 'random'], data() { return { baseArr: [] } }, //.... methods: { handleInit() { let spKey = this.spKey; this.baseArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']; if (this.random && this.random != 'false') { this.baseArr.sort(function() { return Math.random() - Math.random(); }); } this.baseArr.splice(this.baseArr.length - 1, 0, spKey); } } } </script>
将键位打乱顺序其实也很简单,只要通过数组的 sort 方法。sort 方法可以接收一个函数作为参数,若函数返回正数则交换前后两项的位置,若函数返回负数则不作交换。所以将两个随机数相减的结果返回,即可将键位数组随机排序。
下面看看在组件内部是如何触发 change-event 的。
handleInput()
<template> <p> </p> <p> </p> <p>{{item}}</p> <p></p> //键盘图标 //... </template> <script> export default { data() { return { inputStr: '' } }, //... methods: { handleInput(value) { this.inputStr += value; this.$emit('change-event', this.inputStr, value); } } } </script>
增加了 max 属性后修改方法如下:
handleInput(value) { let max = Number(this.max); if (!isNaN(max) && this.inputStr.length+1 > max) { return; } this.inputStr += value; this.$emit('change-event', this.inputStr, value); }
最后看看退格删除是如何实现的。
handleDelete()
handleDelete() { let str = this.inputStr; if (!str.length) return; this.inputStr = str.substring(0, str.length - 1); this.$emit('change-event', this.inputStr); }
上面的例子都是些核心代码的片段,并且其他辅助函数并未列出,想查看完整的代码请看源码。
相关推荐:
The above is the detailed content of Detailed explanation of abstract Vue public components. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.