


In-depth understanding of the three APIs in the vue component: prop, slot and event
No matter how complex the component is, it must be composed of props, events and slots. The following article will take you to understand the prop, slot and event in the vue component and see how to write these three APIs. I hope it will be helpful to you!
Question introduction
Have you encountered the following scenario: During development, you encounter some particularly common displays or functions and want to extract them and encapsulate them into An independent component that is then shared for use by other developers.
To encapsulate a component, we first understand the basic composition of the component. No matter how complex the component is, it must be composed of prop, event and slot. The process of writing components is the process of designing these three APIs. Similarly, if you want to read components written by others, you can also quickly understand them through these three APIs. [Related recommendations: "vue.js Tutorial"]
So how should we write these three APIs: prop, event, and slot?
Property prop
prop is used to define which properties the component can accept.
Reading the vue official website, we know that prop can be written in an array or object. For convenience, many people directly use the array writing method of prop, which is not rigorous. When writing general components, we should use the object writing method of prop as much as possible.
You can see the following code:
app.component('my-component', { props: { // 基础的类型检查 (`null` 和 `undefined` 会通过任何类型验证) propA: Number, // 多个可能的类型 propB: [String, Number], // 必填的字符串 propC: { type: String, required: true }, // 带有默认值的数字 propD: { type: Number, default: 100 }, // 带有默认值的对象 propE: { type: Object, // 对象或数组默认值必须从一个工厂函数获取 default() { return { message: 'hello' } } }, // 自定义验证函数 propF: { validator(value) { // 这个值必须匹配下列字符串中的一个 return ['success', 'warning', 'danger'].includes(value) } }, // 具有默认值的函数 propG: { type: Function, // 与对象或数组默认值不同,这不是一个工厂函数 —— 这是一个用作默认值的函数 default() { return 'Default function' } } } })
I believe everyone can see that prop uses the object writing method. We can verify whether the incoming attributes are correct and give prompts in time. This is This is especially useful when we write independent components.
Since vue must follow the one-way data flow principle, we should not try to modify the prop value and need to use other solutions.
Common solutions for modifying prop values
1. Prop passes the initial value and assigns it to data
props: ['initialCounter'], data() { return { counter: this.initialCounter } }
2. Receive prop values by calculating attributes
props: ['size'], computed: { normalizedSize() { return this.size.trim().toLowerCase() } }
Slot slot
The slot slot is used to distribute the content of the component, such as
<todo-button> Add todo </todo-button>
<!-- todo-button 组件模板 --> <button class="btn-primary"> <slot></slot> </button>
When rendering, it will be replaced by Add todo, such as
<!-- 渲染 HTML --> <button class="btn-primary"> Add todo </button>
This is the most basic usage of slot. It is derived from named slots. As the name suggests, it is to distinguish slots. Multiple slots can be set. For example,
<div class="container"> <header> <slot name="header"></slot> </header> <main> <slot></slot> </main> <footer> <slot name="footer"></slot> </footer> </div>
sometimes encounters setting backup information for slots. Then you can use it like this:
<button type="submit"> <slot>Submit</slot> </button>
The backup information of the slot is Submit
Event event
Event name
When the child component The data has been modified. When you want to notify the parent component, you can use the event event, as follows:
// 子组件 this.$emit('myEvent')
// 父组件 <my-component @my-event="doSomething"></my-component>
It can be seen that when the child component calls, the event name is camel case, while the event name of the parent component is kebab-case name.
Custom events
You can customize events through the emits option, such as
app.component('custom-form', { emits: ['inFocus', 'submit'] })
It should be noted that if the custom event is the same as the native event , such as click, then the custom event will replace the native event
Organization of the component
Introduce a picture from the official website to
The page is equivalent to a tree composed of components. Each component may have parent components and sub-components. The attribute prop allows the parent component to pass properties to the sub-component, and the event event allows the sub-component to pass information to the parent component. The slot slot is used by the parent component to distribute content.
Summary
In addition to these three APIs, components also have other contents, such as life cycle, mix-in, calculated properties, etc., but for component development, this Three APIs are enough. After mastering these three APIs, the only thing left is to decouple the interaction logic of the components, try to distribute different functions to different sub-components, and then build a component tree.
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of In-depth understanding of the three APIs in the vue component: prop, slot and event. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics


![How to solve '[Vue warn]: Missing required prop' error](https://img.php.cn/upload/article/000/887/227/169304743965914.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
How to solve the "[Vuewarn]:Missingrequiredprop" error When developing Vue applications, you sometimes encounter a common error message: "[Vuewarn]:Missingrequiredprop". This error usually refers to the lack of required property values in the component, causing the component to fail to render properly. The solution to this problem is simple. We can avoid and deal with this error through some skills and regulations. Here are some solutions

Event processing library in PHP8.0: Event With the continuous development of the Internet, PHP, as a popular back-end programming language, is widely used in the development of various Web applications. In this process, the event-driven mechanism has become a very important part. The event processing library Event in PHP8.0 will provide us with a more efficient and flexible event processing method. What is event handling? Event handling is a very important concept in the development of web applications. Events can be any kind of user row

Vue component communication: Use $destroy for component destruction communication In Vue development, component communication is a very important aspect. Vue provides a variety of ways to implement component communication, such as props, emit, vuex, etc. This article will introduce another method of component communication: using $destroy for component destruction communication. In Vue, each component has a life cycle, which includes a series of life cycle hook functions. The destruction of components is also one of them. Vue provides a $de

With the continuous development of front-end technology, Vue has become one of the popular frameworks in front-end development. In Vue, components are one of the core concepts, which can break down pages into smaller, more manageable parts, thereby improving development efficiency and code reusability. This article will focus on how Vue implements component reuse and extension. 1. Vue component reuse mixins Mixins are a way to share component options in Vue. Mixins allow component options from multiple components to be combined into a single object for maximum

Vue Practical Combat: Date Picker Component Development Introduction: The date picker is a component often used in daily development. It can easily select dates and provides various configuration options. This article will introduce how to use the Vue framework to develop a simple date picker component and provide specific code examples. 1. Requirements analysis Before starting development, we need to conduct a requirements analysis to clarify the functions and characteristics of the components. According to the common date picker component functions, we need to implement the following function points: Basic functions: able to select dates, and

Vue component communication: using watch and computed for data monitoring Vue.js is a popular JavaScript framework, and its core idea is componentization. In a Vue application, data needs to be transferred and communicated between different components. In this article, we will introduce how to use Vue's watch and computed to monitor and respond to data. watch In Vue, watch is an option, which can be used to monitor the changes of one or more properties.

Steam's Summer Sale has previously played host to some of the best game discounts, and this year seems to be stacking up for another home run by Valve. A trailer (watch below) teasing some of the Steam Summer Sale discounted games was just released i

Vue is a popular JavaScript framework that provides a wealth of tools and features to help us build modern web applications. Although Vue itself already provides many practical functions, sometimes we may need to use third-party libraries to extend Vue's capabilities. This article will introduce how to use third-party libraries in Vue projects and provide specific code examples. 1. Introduce third-party libraries The first step to using third-party libraries in a Vue project is to introduce them. We can introduce it in the following ways
