咔~

导航

理解vue中的slot与slot-scope

vue的slot和slot-scope

对于vue的slot和slot-scope在写vue项目的时候总是很朦胧!vue的文档有比较精简。vue slot文档

先说说slot是啥!都知道的slot叫插槽,其实也好理解,通俗点就是插到某一部分(-_-||)PS:想象一下电脑,有插CPU的,有插显卡的,有插内存的,有插硬盘的~。术语的话就是占位符吧(至少我是这么理解的)。作用就是内容的分发。

值得注意的是:内容要写在父组件中,然后分给需要的子组件。当slot多个时,可以通过name来加以区分,这就是所谓的具名插槽

举个栗子:

  • 默认插槽

父组件:

 1 <template>
 2     <div class="father">
 3         <h3>这里是菜单</h3>
 4         <child>
 5             <div class="list">
 6               <li>口水鸡</li>
 7               <li>口水鸭</li>
 8               <li>口水猪</li>
 9               <li>口水驴</li>
10               <li>口水羊</li>
11               <li>口水牛</li>
12             </div>
13         </child>
14     </div>
15 </template>

  子组件:

 

1 <template>
2     <div class="child">
3         <h3>这里是餐桌点餐</h3>
4         <slot></slot>
5     </div>
6 </template>

 

  • 具名插槽 PS:官网案例

  父组件:

 

 1 <base-layout>
 2   <template slot="header">
 3     <h1>Here might be a page title</h1>
 4   </template>
 5 
 6   <p>A paragraph for the main content.</p>
 7   <p>And another one.</p>
 8 
 9   <template slot="footer">
10     <p>Here's some contact info</p>
11   </template>
12 </base-layout>

  子组件:

1 1 <base-layout>
2 2   <h1 slot="header">Here might be a page title</h1>
3 3 
4 4   <p>A paragraph for the main content.</p>
5 5   <p>And another one.</p>
6 6 
7 7   <p slot="footer">Here's some contact info</p>
8 8 </base-layout>

  这两者就是多了个name,不过一般都会加上name,项目中不会只有一个插槽。

  再说说slot-scope,跟官网一样,我个人觉得slot-scope就是作用域插槽。并且他是接收子组件传来的数据。

  举个栗子:

  • 作用域插槽

  父组件:

 1 <template>
 2     <div class="father">
 3     <h3>这里是父组件</h3>
 4     <slot-scope-child>
 5         <template slot-scope="user">
 6             <ul>
 7                 <li v-for="(item, index) in user.data" :key="index">{{item}}</li>
 8             </ul>
 9         </template>
10     </slot-scope-child>
11   </div>
12 </template>
13 <script>
14 import SlotScopeChild from '@/common/SloteScopeChild'
15 export default {
16     components: {
17         SlotScopeChild
18     }
19 }
20 </script>
21 <style scoped>
22 </style>

 

  子组件:

 1 <template>
 2   <div class="child">
 3     <h3>这里是子组件</h3>
 4     <slot :data="data"></slot>
 5   </div>
 6 </template>
 7 <script>
 8 export default {
 9     data: function(){
10       return {
11         data: ['空空如也','悟空','成都','七月上','病变','走马']
12       }
13     }
14 }
15 </script>

  然后你就会发现,子组件里面的数据会展示出来。这也就是slot-scope。就是带着数据跑。数据在子组件,然后绑到父组件,父组件就可以使用了。这个在elementUI中展示的很好。

  这大概就是我的理解~新手勿怪!错误请多包涵指正。

 

现在再看,2-21号追加的内容,我承认会给我分销,但是内容真的很好。

 

posted on 2018-10-10 15:34  咔~  阅读(12843)  评论(0编辑  收藏  举报