做用:官方解釋就是vue實現一套內容分發機制,將
,就是視圖層和數據層進行展現的時候不要直接綁定數據,而是進行數據的上傳
我的理解,就仍是父子組件的傳值
就像是父組件你把東西給我,我用用,而後我把我所有的加上你給個人一塊給你
子組件:vue
<template> <div> <h2>你叫什麼名字</h2> <slot></slot> </div> </template> <script> export default{ name:'children' } </script>
父組件:java
<template> <div> <p>使用solt傳值:我來告訴你你叫什麼名字</p> <div style="color:red;"> <children> <div>你的名字叫小坦克</div> </children> </div> </div> </template> <script> import children from "./zi"; export default { components: { children } }; </script>
舉例子:
子組件服務器
<template> <div> <div> <h2>爸爸的名字</h2> <slot name="fathername"></slot > </div> <div> <h2>媽媽的名字</h2> <slot name="mothername"></slot > </div> </div> </template> <script> export default { name: "children" }; </script>
父組件:函數
<template> <div> <p>使用solt傳值:爸爸媽媽的名字叫什麼</p> <div style="color:red;"> <children> <template v-slot:fathername> <p>小坦克的爸爸</p> </template> <template v-slot:mothername> <p>小坦克的媽媽</p> </template> </children> </div> </div> </template> <script> import children from './zi' export default { components:{ children } }; </script>
注意:code
有個描述寫的很好component
做用域插槽其實就是帶數據的插槽,即帶參數的插槽,簡單的來講就是子組件提供給父組件的參數,該參數僅限於插槽中使用,父組件可根據子組件傳過來的插槽數據來進行不一樣的方式展示和填充插槽內容。對象
例子:簡單點實例,簡單瞭解,明白用法
子組件blog
<template> <div class="card-wrap"> <div class="foot"> <slot name="todo" v-bind:user="user"> </slot> </div> </div> </template> <script> export default { data(){ return{ user:{ lastname:'qiao', age:12, firstName:'zhang' } } } } </script>
父組件:事件
<Card> <template v-slot:todo="slotProps"> {{slotProps.user.age}} {{slotProps.user.lastname}} </template> </Card> //slotProps 能夠隨意命名 //slotProps 接取的是子組件標籤slot上屬性數據的集合全部v-bind:user="user"
這只是簡單的應用
在此有一個例子用來顯示
https://www.jianshu.com/p/e10baeff888d
介紹相應的插槽使用
加以理解
有個例子
就是寫商城 你想裏邊不是有不少的 欄目 商品對吧
在咱們的初衷確定是要在寫的時候進行相應的分類的,細化到模塊進行書寫對吧,而後商品列表原本就不少,從服務器取回數據要進行相應的渲染,確定要用到循環,每一個商品的格式都是同樣的啊
步驟:
1.首先咱們把一個商品單獨列出來,寫成一個小組件,商品卡片,例如咱們新建一個 food.vue
而後呢咱們在 商品展現列表 foodlist.vue 裏面進行數據的展現
就是取到數據 寫一個 v-for 循環商品卡片顯示
//明白代碼的意思就行 <food v-for="(item , index) in commodities :fooddata="fooddata" @clickfood="onFoodClick" "></food>
2.在子組件裏面進行數據的上傳到父組件
意思就是food.vue 組件使用點擊事件上傳本身id 能夠在父組件裏面進行相應的操做好比跳轉到詳情頁
拓展:
好比上邊的那個圖片 裏面有好幾個相應的欄目,每一個裏面都有相應的商品那咱們就能夠用插槽了是否是 (插槽不就是能夠把相應的要展現的東西模板啥的傳進去顯示嗎 這是我看到這個例子的第一反應) 對吧 在整個的首頁上面 把每一個欄目抽成組件 來用 在每一個組件裏面顯示相應的商品卡片就是插槽
大致邏輯就是這樣 實現 組件和業務的分離
可是具體的細化我沒有認真理解透 有時間再來弄
1:縮寫 (v-slot:) 替換爲字符 #。例如 v-slot:header 能夠被重寫爲 #header:
2.廢棄的語法 可是還在用 在有的組件庫裏面會有的
//在 <template> 上使用特殊的 slot attribute,能夠將內容從父級傳給具名插槽 <template slot="header"> <h1>Here might be a page title</h1> </template> // 或者直接把 slot attribute 用在一個普通元素上: <h1 slot="header">Here might be a page title</h1> //或者有 slot-scope attribute 的做用域插槽 //在 <template> 上使用特殊的 slot-scope attribute,能夠接收傳遞給插槽的 prop (把這裏提到過的 <slot-example> 組件做爲示例): <slot-example> <template slot="default" slot-scope="slotProps"> {{ slotProps.msg }} </template> </slot-example> //這裏的 slot-scope 聲明瞭被接收的 prop 對象會做爲 slotProps 變量存在於 <template> 做用域中。你能夠像命名 JavaScript 函數參數同樣隨意命名 slotProps。