网站链接: 我爱捣鼓
当前位置: 首页 > 前端开发 > Vue

如何通过插槽来给子组件分配内容?

2023/6/1 20:40:03

插槽在vue的开发中显得很有用处,今天我们就来说说如何通过插槽来给子组件分配内容? 一些情况下我们会希望能和 HTML 元素一样向组件中传递内容:<AlertBox> Something bad happened.</AlertBox> 我们期望能渲染成这样: 这可以通过 V…

        插槽在vue的开发中显得很有用处,今天我们就来说说如何通过插槽来给子组件分配内容?

        一些情况下我们会希望能和 HTML 元素一样向组件中传递内容:


<AlertBox>
  Something bad happened.
</AlertBox>

        我们期望能渲染成这样:

image.png

        这可以通过 Vue 的自定义 <slot> 元素来实现:

<template>
  <div class="alert-box">
    <strong>This is an Error for Demo Purposes</strong>
    <slot />
  </div>
</template>
<style scoped>
.alert-box {
  /* ... */
}
</style>

        如上所示,我们使用 <slot> 作为一个占位符,父组件传递进来的内容就会渲染在这里。

        我们通过一个实例来加深对插槽的理解。

App.vue

<script>
import AlertBox from './AlertBox.vue'
  
export default {
  components: { AlertBox }
}
</script>
<template>
<AlertBox>
  Something bad happened.
</AlertBox>
</template>

AlertBox.vue


<template>
  <div class="alert-box">
    <strong>Error!</strong>
    <br/>
    <slot />
  </div>
</template>
<style scoped>
.alert-box {
  color: #666;
  border: 1px solid red;
  border-radius: 4px;
  padding: 20px;
  background-color: #f8f8f8;
}
  
strong {
color: red;    
}
</style>

image.png

        通过以上内容我们知道了vue 中如何通过插槽来给子组件分配内容。感谢您访问“我爱捣鼓(www.woaidaogu.com)”网站的内容,希望对大家有所帮助!引用本文内容时,请注明出处!谢谢合作!

相关资讯

  • vue兄弟平级组件如何传递参数值?

    vue组件传值不外乎三种,父传子、子传父、平级,今天我们就来着重说说vue平级组件如何传递参数值? 假设你有两个Vue组件需要通信: A 和 B ,A组件按钮上面绑定了点击事件,发送一则消息,B组件接收。初始化,全局创建$bus 直接在项目中的 main.js 初始化 …

    2023/1/7 13:08:32