slot插槽

用来访问被插槽分发的内容。每个具名插槽有其相应的 property (例如:v-slot:foo 中的内容将会在 vm.$slots.foo 中被找到)。default property 包括了所有没有被包含在具名插槽中的节点,或 v-slot:default 的内容。
请注意插槽不是响应性的。如果你需要一个组件可以在被传入的数据发生变化时重渲染,我们建议改变策略,依赖诸如 propsdata 等响应性实例选项。
注意:v-slot:foo2.6 以上的版本才支持。对于之前的版本,你可以使用废弃了的语法。

在使用渲染函数书写一个组件时,访问 vm.$slots 最有帮助。
v-slot 指令自 Vue 2.6.0 起被引入,提供更好的支持 slot 和 slot-scope attribute 的 API 替代方案。v-slot 完整的由来参见这份 RFC。在接下来所有的 2.x 版本中 slotslot-scope attribute 仍会被支持,但已经被官方废弃且不会出现在 Vue 3 中。

html 复制代码
<!-- 在表达式中使用 ES2015 解构 -->
<todo-list v-bind:todos="todos">
  <template slot="operation" slot-scope="{ todo }"> 
    <span v-if="todo.isComplete">✓</span>
    {{ todo.text }}
  </template>
   <template slot="default" slot-scope="slotProps">
    {{ slotProps.msg }}
  </template>
</todo-list>
html 复制代码
<todo-list v-bind:todos="todos">
  <template v-slot:operation="{ todu }" > 
    <span v-if="todo.isComplete">✓</span>
    {{ todo.text }}
  </template>
   <template v-slot:default="slotProps">
    {{ slotProps.msg }}
  </template>
</todo-list>
javascript 复制代码
Vue.component('blog-post', {
  render: function (createElement) {
    var header = this.$slots.header
    var body   = this.$slots.default
    var footer = this.$slots.footer
    return createElement('div', [
      createElement('header', header),
      createElement('main', body),
      createElement('footer', footer)
    ])
  }
})

v-slot:other="otherSlotProps" 这样的语法来将数据传递给插槽

ChildComponent 的模板代码:

html 复制代码
<template>
  <div>
    <slot name="other" :otherSlotProps="otherSlotProps"></slot>
  </div>
</template>
<script>
export default {
  data() {
    return {
      otherSlotProps: {
        message: 'Hello from parent component'
      }
    };
  }
};
</script>

ParentComponent 的模板代码:

html 复制代码
<template>
  <div>
    <ChildComponent>
      <template v-slot:other="otherSlotProps">
        <p>{{ otherSlotProps.message }}</p>
      </template>
    </ChildComponent>
  </div>
</template>
<script>
	import ChildComponent from './ChildComponent.vue';
	export default {
	  components: {
	    ChildComponent
	  }
	};
</script>
相关推荐
牛奶13 分钟前
200 OK不是"成功"?HTTP状态码潜规则
前端·http·浏览器
Hilaku1 小时前
OpenClaw 很爆火,但没人敢聊它的权限安全🤷‍♂️
前端·javascript·程序员
ConardLi1 小时前
OpenClaw 完全指南:这可能是全网最新最全的系统化教程了!
前端·人工智能·后端
丁哥2 小时前
99.9%纯AI 做了一个ICO图标生成器(免费 全尺寸 不限文件大小)2ICO.CN欢迎品鉴
前端
兆子龙2 小时前
React Native 完全入门:从原理到实战
前端·javascript
哇哇哇哇2 小时前
vue3 watch解析
前端
SuperEugene2 小时前
Vite 实战教程:alias/env/proxy 配置 + 打包优化避坑|Vue 工程化必备
前端·javascript·vue.js
leafyyuki2 小时前
用 AI 和 SDD 重构 Vue2 到 Vue3 的实践记录
前端·人工智能
德育处主任3 小时前
『NAS』一句话生成网页,在NAS部署UPage
前端·javascript·aigc
前端老兵AI3 小时前
前端工程化实战:Vite + ESLint + Prettier + Husky 从零配置(2026最新版)
前端·vite