让前端飞前端开发笔记

vue 组件之scope 属性,组件如何给插槽传数据

2018-10-24  本文已影响48人  一笑解qian愁

一个组件如何给当做插槽的组件传参?平时我们使用查槽都是这么用的。插槽的直接接受页面的数据。常规用法

<template>
    <div>
        <father-compoent>
      <!--指定将子组件放到父组件中的name=list的slot标签的位置-->
            <child-component slot="list" :data="arr"></child-component>
        </father-compoent>
    </div>
</template>
<script>
export default {
    data(){
        arr:[1,2,3,4]
    },
}
</script>

那么问题来了目前有个需求是需要在页面传入一个数据,在父组件中对数据做一些处理然后再传给子组件中去遍历,怎么做呢?说白了困难点就是在组件中给组件内的插槽传数据。这下就需要用的scope这个属性了
父组件如下

<template>
    <div>
        <father-compoent>
        <!--注意:list字段随意写,但是要和外层使用时一致-->
           <slot name="list" :list="arr"><slot>
        </father-compoent>
    </div>
</template>
<script>
export default {
    data(){
        arr:[1,2,3,4]
    },
    
}
</script>

重点来了

<template>
    <div>
        <father-compoent>
        <!--这里需要用一个templat标签来定义从父组件来接受的参数的名称-->
            <template slot="list" scope="scope">
            <!--注意,scope.xxx这个字段要和父组件内传的字段一致-->
                        <child-component  :data="scope.list" :data2="arr"></child-component>
            </template>
        </father-compoent>
    </div>
</template>
<script>
export default {
    data(){
        arr:[1,2,3,4]
    },
    
}
</script>

子组件中的scope.list就是父组件传过来的数据,而arr就是页面中的数据
就这样通过scope属性来搭桥,插槽位置的组件就可以拿到父组件的数据了,同时子组件同样也可以接受页面上的数据arr,这样大功告成

上一篇 下一篇

猜你喜欢

热点阅读