# Vue Template中slot-scope/scope如何使用
## 前言
在Vue.js的組件化開發中,插槽(Slot)是實現內容分發的重要機制。而`slot-scope`(Vue 2.6.0以下)和`scope`(更早版本)則是實現**作用域插槽**的關鍵特性。本文將詳細解析其用法、區別以及實際應用場景。
---
## 一、基礎概念
### 1. 什么是作用域插槽?
作用域插槽允許子組件將數據傳遞到父組件中定義的插槽內容里,實現**子傳父**的數據流動。
### 2. 版本差異
- Vue 2.6.0+:使用`v-slot`指令(推薦)
- Vue 2.5.0-2.6.0:使用`slot-scope`屬性
- 更早版本:使用`scope`屬性(已廢棄)
---
## 二、基本語法
### 1. 子組件定義插槽
子組件通過`<slot>`暴露數據:
```html
<!-- ChildComponent.vue -->
<template>
<div>
<slot :user="userData" :status="isActive"></slot>
</div>
</template>
<script>
export default {
data() {
return {
userData: { name: 'Alice', age: 25 },
isActive: true
}
}
}
</script>
<child-component>
<template slot-scope="props">
<p>用戶名: {{ props.user.name }}</p>
<p>狀態: {{ props.status ? '活躍' : '離線' }}</p>
</template>
</child-component>
<child-component>
<template v-slot:default="props">
<p>用戶名: {{ props.user.name }}</p>
<p>狀態: {{ props.status ? '活躍' : '離線' }}</p>
</template>
</child-component>
<template v-slot="{ user, status }">
<p>{{ user.name }} - {{ status }}</p>
</template>
子組件:
<slot name="header" :title="pageTitle"></slot>
父組件:
<template v-slot:header="{ title }">
<h1>{{ title }}</h1>
</template>
<template v-slot:[dynamicSlotName]="props">
<!-- 內容 -->
</template>
<!-- TableComponent.vue -->
<template>
<table>
<tr v-for="(item, index) in data">
<slot :row="item" :index="index"></slot>
</tr>
</table>
</template>
<!-- 使用 -->
<table-component :data="users">
<template v-slot="{ row, index }">
<td>{{ index + 1 }}</td>
<td>{{ row.name }}</td>
</template>
</table-component>
<!-- ConditionalWrapper.vue -->
<template>
<div v-if="condition">
<slot :extraData="dataForSlot"></slot>
</div>
<slot v-else name="fallback"></slot>
</template>
<template>
標簽上可以!v-slot:header
可簡寫為 #header
作用域插槽會有輕微性能開銷,但在大多數場景下可忽略不計
data
作用域插槽是Vue組件通信的強力工具,尤其適合需要高度自定義的組件場景。通過本文的講解,希望你能掌握: - 新舊語法的區別與遷移 - 解構等高級用法 - 實際項目中的落地實踐
官方文檔參考:
Vue 2.x Slots
Vue 3.x Slots “`
注:本文以Vue 2.x為主要版本說明,Vue 3.x的用法基本相同,但建議優先查閱最新文檔。實際字數約1200字(含代碼示例)。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。