• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Vue.js特性Scoped Slots的浅析

vue 搞代码 4年前 (2022-01-08) 17次浏览 已收录 0个评论

这篇文章主要介绍了Vue.js特性Scoped Slots的浅析,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

什么是scoped slots

A scoped slot is a special type of slot that functions as a reusable template (that can be passed data to) instead of 本文来源gaodai#ma#com搞*!代#%^码$网!already-rendered-elements.

上面是官方的定义。

作用域插槽(Scoped Slots)是vue.js中一个非常有用的特性,它可以使组件更加通用和复用。唯一的问题是理解起来比较困难。试图去让你理解父与子作用域的交织关系,像解决一道数学难题。

简单点说slot就是插槽,它是可以被替换掉的,替换它的内容是可以拿到当前组件的上下文的
(为了简单起见,以下例子以模板为主)

举个简单的例子

 //button.vue  <button class="btn">  //相当于是占位 </button>
 //app.vue  <div id="app"> <button>Buton with text</button><button> <i class="fa fa-copy"></i>//这里取代了slot的位置 </button><button> <i class="fa fa-user"></i>Profile </button></div>

slot其实就是一个占位,button.vue的slot位置会被app.vue里面的替换了。

复杂例子1:slot内的东西可以获取父组件的上下文信息

 //list.vue  <div> //这里是slot的占位 </div>
 //app.vue  <div id="app">  <div class="list-item1">//这里可以获取到item,item原本是属于List组件内部的。也就是说slot获取了父组件的上下文。 {{row.item.text}} </div></div>

解释见上面代码注释。注意一点的是slot-scope=”row” 这里的名字(row)是可以任意取的。

named slots

可以直接放到普通标签上面,可以放template标签上

slot里面的作用域是普通标签或者template是一致的。不能访问父组件的作用域。

复杂例子2:slot里面是可以放东西的,是默认的模板,可被替换。

 //table.vue  <table class="table"> <thead> //这里定义了一个slot,名字叫columns,也就是说这里的内容是可以被替换掉的 <th> {{column}} </th></thead><tbody> <tr> //这里slot有一个prop是row <td> {{itemValue(item, column)}} </td></tr></tbody></table>
 //app.vue  <div id="app">  <div class="table-separator"></div> //这里有一个slot="columns",意思是替换table.vue里面名字叫columns的slot <th>Title</th><th> <i class="fa fa-images"></i> Image </th><th class="actions-row"> <i class="fab fa-vuejs vue-icon"></i> Actions </th>//这里替换table.vue里面slot为row的内部内容 <td class="bold-row"> {{row.title}} </td><td class="img-row"> </td><td class="actions-row"> <button> <i class="fa fa-edit"></i></button><button type="danger"> <i class="fa fa-trash"></i></button></td></div>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网

以上就是Vue.js特性Scoped Slots的浅析的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Vue.js特性Scoped Slots的浅析

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址