Home  >  Article  >  Web Front-end  >  In-depth understanding of the three APIs in the vue component: prop, slot and event

In-depth understanding of the three APIs in the vue component: prop, slot and event

青灯夜游
青灯夜游forward
2021-11-23 19:14:062231browse

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!

In-depth understanding of the three APIs in the vue component: prop, slot and event

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(&#39;myEvent&#39;)
// 父组件
<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(&#39;custom-form&#39;, {
  emits: [&#39;inFocus&#39;, &#39;submit&#39;]
})

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

In-depth understanding of the three APIs in the vue component: prop, slot and event

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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete