First, why there are slots

  • Pass custom content from parent to child components

What is a slot?

1. What is a slot

  • By definition, a slot is a structure that inserts anything into the current page.

2. Slot classification

  • (1) Anonymous slot: a slot without a name
  • (2) Named slot: a slot with a name (name attribute)
  • (3) Scope slot: the data in the child component can only be accessed by the child component, but our slots are often defined in the parent component. At this time, we need scope slot to get through the relationship between them, and then we can happily use the data of the child component in the parent component

How to use slot?

1. Anonymous slot

A. Define slots in subcomponents

  • through<slot></slot>That is, the slot component defines a slot where a slot is needed in a child component

B. Fill slots in the parent component

  • (1) Write the contents of the slot directly to the child component registered by the parent component
  • (2) pass in the parent component<template #default><template>To insert content into child components, where default stands for default slot

2. Named slot

A. Define slots in subcomponents

  • As with anonymous slots, slots are defined through the slot component built into Vue, except that named slots have a name and there will be onenameProperty defines the name of the slot, written like this:<slot name=" slot name "></slot>

B. Fill slots in the parent component

  • through<template v-slot: slot name ></template>To insert content into the corresponding slot of the child component, or through#L instead ofv-slot:

3. Scope slot

  • Scope is a set of search variable rules, the parent component has its own scope, can only find themselves in their own scope definition of variables, child components, too, we use the slot is usually filled with a slot in the parent component, if you want to get to the data in the child components, the use scope slot, then see how to use the scope slot

A. the child component

  • Data is passed by V-bind, and the attributes in the slot bound by V-bind are called slot prop

B. the parent component

  • (1) Direct acquisition

  • (2) Obtained through deconstruction assignment

Four, some small details

  • You can define default display content (backup content) in child component slots, backup content when no slot is filled in the parent component, and new content filled in the parent component once there is a filled slot