slot 怎么传值给子组件

hongxia1 32 0

在 Vue.js 中,使用具名插槽 <slot name="slotName"></slot> 可以让父组件向子组件传递特定的内容。要将值传递给子组件的具名插槽,可以使用 v-slot 指令。以下是具体的步骤和示例:

1. 在子组件中定义具名插槽

首先,在子组件中定义具名插槽:

<template>  
  <div>  
    <h2>子组件内容</h2>  
    <slot name="slotName"></slot> <!-- 具名插槽 -->  
  </div>  
</template>  

<script>  
export default {  
  name: 'ChildComponent'  
}  
</script>

2. 在父组件中使用具名插槽

在父组件中使用子组件,并通过 v-slot 指令传递内容到具名插槽:

<template>  
  <div>  
    <ChildComponent>  
      <template v-slot:slotName>  
        <p>这是传递给具名插槽的内容。</p>  
      </template>  
    </ChildComponent>  
  </div>  
</template>  

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

export default {  
  components: {  
    ChildComponent  
  }  
}  
</script>

3. 传递数据到具名插槽

如果需要从父组件向子组件传递数据,可以使用 props。以下是一个示例:

修改子组件以接收 props

<template>  
  <div>  
    <h2>子组件内容</h2>  
    <slot name="slotName" :message="message"></slot> <!-- 具名插槽,传递数据 -->  
  </div>  
</template>  

<script>  
export default {  
  name: 'ChildComponent',  
  props: {  
    message: {  
      type: String,  
      default: '默认消息'  
    }  
  }  
}  
</script>

在父组件中使用具名插槽并接收数据

<template>  
  <div>  
    <ChildComponent :message="parentMessage">  
      <template v-slot:slotName="{ message }">  
        <p>这是传递给具名插槽的内容:{{ message }}</p>  
      </template>  
    </ChildComponent>  
  </div>  
</template>  

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

export default {  
  components: {  
    ChildComponent  
  },  
  data() {  
    return {  
      parentMessage: '来自父组件的消息'  
    };  
  }  
}  
</script>

总结

  • 在子组件中使用 <slot name="slotName"></slot> 定义具名插槽。

  • 在父组件中使用 <template v-slot:slotName> 传递内容。

  • 可以通过 props 将数据传递给具名插槽,并在父组件中接收这些数据。


上一篇宝塔Linux面板最新自编译Nginx云锁模块

下一篇当前文章已是最新一篇了

  • 评论列表

留言评论