vue2 封装插槽组件

安装 element-ui

npm install element-ui --save ---force

main.js 导入

import Vue from 'vue';

import ElementUI from 'element-ui';

import 'element-ui/lib/theme-chalk/index.css';

import App from './App.vue';

Vue.use(ElementUI);

new Vue({ el: '#app', render: h => h(App) });

创建一个插槽组件

  • 具名插槽 (Named Slots) :允许你在组件中定义多个插槽,并为它们命名。在上面的示例中,header 是一个具名插槽。

  • 默认插槽 (Default Slot):如果没有提供具名插槽,插入的内容会放入默认插槽。

使用插槽组件

复制代码
<!-- App.vue -->
<template>
  <div>
    <BaseCard>
      <template v-slot:header>
        <h2>Card Title</h2>
      </template>
      <p>This is the card content.</p>
    </BaseCard>
  </div>
</template>

<script>
import BaseCard from './components/BaseCard.vue'

export default {
  name: 'App',
  components: {
    BaseCard
  }
}
</script>

作用域插槽:

组件:

复制代码
<!-- BaseCard.vue -->
<template>
  <div class="card">
    <div class="card-header">
      <slot name="header" :title="headerTitle"></slot>
    </div>
    <div class="card-body">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BaseCard',
  data() {
    return {
      headerTitle: 'Default Title'
    }
  }
}
</script>

使用:

复制代码
<!-- ParentComponent.vue -->
<template>
  <div>
    <BaseCard>
      <template v-slot:header="slotProps">
        <h2>{{ slotProps.title }}</h2>
      </template>
      <p>This is the card content.</p>
    </BaseCard>
  </div>
</template>

<script>
import BaseCard from './components/BaseCard.vue'

export default {
  name: 'ParentComponent',
  components: {
    BaseCard
  }
}
</script>
相关推荐
奋斗吧程序媛21 小时前
补充一个小知识点:有关@click.native
前端·vue.js
英勇无比的消炎药21 小时前
一行命令背后:TinyRobot CLI 如何重构 AI 对话接入的效率范式
vue.js·aigc
jay神1 天前
基于 FastAPI + Vue 的宠物领养管理系统
前端·vue.js·python·毕业设计·fastapi·宠物
一杯奶茶¥1 天前
水果销售网站 CRM客户信息管理系统 超市管理系 酒店管理系统 健身房管理系统 在线音乐网站 校园招聘系统
java·vue.js·spring boot·mysql·spring·java项目
英勇无比的消炎药1 天前
一站式搞定品牌风格:TinyRobot 主题定制从入门到精通
vue.js
尽欢i1 天前
Vue3 customRef 封神教程:防抖、本地存储、自动埋点一套搞定,模板干干净净
前端·javascript·vue.js
因_崔斯汀1 天前
Vue 模板编译:HTML 是怎么变成 JS 的?
前端·vue.js
英勇无比的消炎药1 天前
样式随心定制:TinyRobot 样式覆写与 CSS 变量实战解析
vue.js
疯狂的魔鬼1 天前
多角色督办任务详情页:从权限矩阵到组件拆分的完整实现
前端·vue.js·架构
英勇无比的消炎药1 天前
拆解内核:深入分析 TinyRobot 输入区组件设计与实现原理
vue.js