The relationship between component parameter passing and slots in vue

In Vue, passing parameters and slots are two different concepts, but there is a certain relationship between them.

Passing parameters refers to passing data between components, which can be realized through props and $emit, provide and inject, Vuex, etc. The purpose of passing parameters is to allow components to share data, thereby realizing communication between components.

A slot is to define one or more slots in a component, and then when the component is used, any content can be inserted into the slot. The purpose of slots is to make components more flexible, and different content can be dynamically inserted according to usage scenarios.

The relationship between parameter passing and slots is that passing parameters can be used to control the contents of a slot. For example, you can pass data to child components through the props attribute, and use slots in the child components to display these data. For another example, you can pass the data in the child component to the parent component through the $emit event, and use slots in the parent component to display the data.

Here's an example that demonstrates how to control content in components by passing parameters and slots:




// 父组件
<template>
  <div>
    <child-component :message="hello">
      <template #default="{ message }">
        <div>{
   
   { message }} World!</div>
      </template>
    </child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      hello: 'Hello'
    }
  }
}
</script>

// 子组件
<template>
  <div>
    <slot :message="message"></slot>
  </div>
</template>

<script>
export default {
  props: {
    message: String
  },
  data() {
    return {
      message: this.message
    }
  }
}
</script>

In the above example, the parent component passes data to the child component through the props attribute, and the child component passes data to the parent component through the slot. Specifically, the parent component passes the data hello to the child component, the child component passes the data message to the slot, and the parent component receives the data through the slot and displays it on the page.

In short, parameter passing and slots are two different concepts, but there is a certain relationship between them. Passing parameters can be used to control the content in the slot, so as to realize communication and dynamic rendering between components.

Guess you like

Origin blog.csdn.net/zhangkunsir/article/details/130369256