国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Vue.js特性Scoped Slots的淺析

2024-05-06 15:42:16
字體:
來源:轉載
供稿:網友

什么是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 already-rendered-elements.

上面是官方的定義。

作用域插槽(Scoped Slots)是vue.js中一個非常有用的特性,它可以使組件更加通用和復用。唯一的問題是理解起來比較困難。試圖去讓你理解父與子作用域的交織關系,像解決一道數學難題。

簡單點說slot就是插槽,它是可以被替換掉的,替換它的內容是可以拿到當前組件的上下文的
(為了簡單起見,以下例子以模板為主)

舉個簡單的例子

//button.vue<template> <button class="btn">  <slot></slot> //相當于是占位 </button></template><script>export default {}</script>
//app.vue<template> <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></template><script> import Button from './components/Button.vue' export default { name: 'app', components: { Button } }</script>

slot其實就是一個占位,button.vue的slot位置會被app.vue里面的替換了。

復雜例子1:slot內的東西可以獲取父組件的上下文信息

//list.vue<template> <div> <slot v-for="item in items"   :item="item">//這里是slot的占位 </slot>  </div></template>
//app.vue<template> <div id="app"> <List :items="listItems">  <div slot-scope="row"  class="list-item1">//這里可以獲取到item,item原本是屬于List組件內部的。也就是說slot獲取了父組件的上下文。  {{row.item.text}} </div> </List> </div></template>

解釋見上面代碼注釋。注意一點的是slot-scope=”row” 這里的名字(row)是可以任意取的。

named slots

可以直接放到普通標簽上面,可以放template標簽上

slot里面的作用域是普通標簽或者template是一致的。不能訪問父組件的作用域。

復雜例子2:slot里面是可以放東西的,是默認的模板,可被替換。

//table.vue<template> <table class="table"> <thead>  <slot name="columns">//這里定義了一個slot,名字叫columns,也就是說這里的內容是可以被替換掉的  <th v-for="column in columns">   {{column}}  </th>  </slot> </thead> <tbody> <tr v-for="item in data">  <slot :row="item">//這里slot有一個prop是row  <td v-for="column in columns"   v-if="hasValue(item, column)">   {{itemValue(item, column)}}  </td>  </slot> </tr> </tbody> </table></template>            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 阿鲁科尔沁旗| 定兴县| 淳安县| 泸溪县| 化州市| 安福县| 湘阴县| 桂东县| 青铜峡市| 苏尼特右旗| 家居| 屯门区| 蓝田县| 毕节市| 揭西县| 舞阳县| 涞水县| 铜川市| 准格尔旗| 甘孜| 安溪县| 烟台市| 大悟县| 丹江口市| 高密市| 衡阳县| 乐清市| 阿拉善左旗| 福鼎市| 大同市| 融水| 沙雅县| 株洲市| 高阳县| 内江市| 文登市| 达孜县| 铜梁县| 营山县| 瑞安市| 富蕴县|