1. 程式人生 > 其它 >vue學習---插槽(slot標籤 與 scope屬性)

vue學習---插槽(slot標籤 與 scope屬性)

插槽

  1. 作用:讓父元件可以向子元件指定位置插入html結構,也是一種元件間通訊的方式,適用於父元件 ===> 子元件

  2. 分類:預設插槽、具名插槽、作用域插槽

  3. 使用方式:

    1. 預設插槽:

      父元件中:
              <Category>
                 <div>html結構1</div>
              </Category>
      子元件中:
              <template>
                  <div>
                     <!-- 定義插槽 -->
                     <slot>插槽預設內容...</slot>
                  </div>
              </template>
      
    2. 具名插槽:

      父元件中:
              <Category>
                  <template slot="center">
                    <div>html結構1</div>
                  </template>
      
                  <template v-slot:footer>
                     <div>html結構2</div>
                  </template>
              </Category>
      子元件中:
              <template>
                  <div>
                     <!-- 定義插槽 -->
                     <slot name="center">插槽預設內容...</slot>
                     <slot name="footer">插槽預設內容...</slot>
                  </div>
              </template>
      
    3. 作用域插槽:

      1. 理解:資料在元件的自身,但根據資料生成的結構需要元件的使用者來決定。(games資料在Category元件中,但使用資料所遍歷出來的結構由App元件決定)

      2. 具體編碼:

        父元件中:
        		<Category>
        			<template scope="scopeData">
        				<!-- 生成的是ul列表 -->
        				<ul>
        					<li v-for="g in scopeData.games" :key="g">{{g}}</li>
        				</ul>
        			</template>
        		</Category>
        
        		<Category>
        			<template slot-scope="scopeData">
        				<!-- 生成的是h4標題 -->
        				<h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
        			</template>
        		</Category>
        子元件中:
                <template>
                    <div>
                        <slot :games="games"></slot>
                    </div>
                </template>
        		
                <script>
                    export default {
                        name:'Category',
                        props:['title'],
                        //資料在子元件自身
                        data() {
                            return {
                                games:['紅色警戒','穿越火線','勁舞團','超級瑪麗']
                            }
                        },
                    }
                </script>