


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!
![如何解决“[Vue warn]: Missing required prop”错误](https://img.php.cn/upload/article/000/887/227/169304743965914.jpg)
如何解决“[Vuewarn]:Missingrequiredprop”错误在开发Vue应用程序时,有时会遇到一个常见的错误信息:“[Vuewarn]:Missingrequiredprop”。这个错误通常指的是在组件中缺少必需的属性值,导致组件无法正常渲染。解决这个问题的方法很简单,我们可以通过一些技巧和规范来避免和处理这个错误。以下是一些解

Vue组件通信:使用$destroy进行组件销毁通信在Vue开发中,组件通信是非常重要的一个方面。Vue提供了多种方式来实现组件通信,比如props和emit、vuex等。本文将介绍另一种组件通信方式:使用$destroy进行组件销毁通信。在Vue中,每个组件都有一个生命周期,其中包含了一系列的生命周期钩子函数。组件的销毁也是其中之一,Vue提供了一个$de

随着前端技术的不断发展,Vue已经成为了前端开发中的热门框架之一。在Vue中,组件是其中的核心概念之一,它可以将页面分解为更小,更易管理的部分,从而提高开发效率和代码复用性。本文将重点介绍Vue如何实现组件的复用和扩展。一、Vue组件复用mixinsmixins是Vue中的一种共享组件选项的方式。Mixins允许将多个组件的组件选项合并成一个对象,从而最大

Vue实战:日期选择器组件开发引言:日期选择器是在日常开发中经常用到的一个组件,它可以方便地选择日期,并提供各种配置选项。本文将介绍如何使用Vue框架来开发一个简单的日期选择器组件,并提供具体的代码示例。一、需求分析在开始开发之前,我们需要进行需求分析,明确组件的功能和特性。根据常见的日期选择器组件功能,我们需要实现以下几个功能点:基础功能:能够选择日期,并

Vue组件通信:使用watch和computed进行数据监听Vue.js是一款流行的JavaScript框架,它的核心思想是组件化。在一个Vue应用中,不同的组件之间需要进行数据的传递和通信。在这篇文章中,我们将介绍如何使用Vue的watch和computed来进行数据的监听和响应。watch在Vue中,watch是一个选项,它可以用来监听一个或多个属性的变

Vue中的插槽相信使用过Vue的小伙伴或多或少的都用过,但是你是否了解它全部用法呢?本篇文章就为大家带来Vue3中插槽的全部用法来帮助大家查漏补缺。

Vue是一款流行的JavaScript框架,它提供了丰富的工具和功能,可以帮助我们构建现代化的Web应用程序。尽管Vue本身已经提供了许多实用的功能,但有时候我们可能需要使用第三方库来扩展Vue的能力。本文将介绍在Vue项目中如何使用第三方库,并提供具体的代码示例。1.引入第三方库在Vue项目中使用第三方库的第一步是引入它们。我们可以通过以下几种方式来引入

Vue中使用slot优化组件的扩展性能在Vue开发中,组件是构建应用界面的重要模块。一个强大而有效的组件可以提高开发效率和代码复用性。然而,随着应用规模的增大,组件的扩展性往往成为一个挑战。为了解决这个问题,Vue提供了一个强大的功能——slot(插槽)。slot是Vue中一种用于向组件传递内容的机制。通过使用slot,我们可以将代码的灵活性和可重用性进一步


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment