目录

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>
本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
百锦再15 分钟前
五种常用的web加密算法
前端·算法·前端框架·web·加密·机密
@大迁世界16 分钟前
彻底改变我 React 开发方式的组件模式
前端·javascript·react.js·前端框架·ecmascript
William Dawson1 小时前
【Vue 3 + Element Plus 实现产品标签的动态添加、删除与回显】
前端·javascript·vue.js
拉不动的猪1 小时前
项目基础搭建时的一些基本注意点
前端·javascript·面试
蕉君桑1 小时前
vue2使用vue-echarts
前端·vue.js·echarts
runnerdancer2 小时前
React+Vite+Typescript项目脚手架模版
前端
Code额2 小时前
ECMAScript 6 新特性(二)
前端·javascript·ecmascript
群联云防护小杜3 小时前
基于AI的Web应用防火墙(AppWall)实战:漏洞拦截与威胁情报集成
前端·分布式·安全·ddos
_清浅3 小时前
JavaScript(JS进阶)
开发语言·前端·javascript·操作系统·html5
葡萄城技术团队3 小时前
如何通过前端表格控件实现自动化报表?1
运维·前端·自动化