Vue 插槽的使用

test.vue

<template>
    <div class="big-box">
        <Parent>
            <Child v-for='items in 5' :key='items'>
                <img :src="imgUrl"/>            
            </Child>
        </Parent>
    </div>
</template>

<script>
    import Parent from '../components/parent'
    import Child from '../components/child'
    export default{
        name:'test',
        data(){
            return{
                imgUrl:require('../assets/image/opencardlogin.png')
            }
        },
        components:{
            Parent,
            Child
        }
    }
</script>

<style>
</style>

-------------------------------------------------------   parent.vue  -----------------------------------------------------------------------

<template>
    <div class="parent">
        <ul>
            <!--利用插槽来代替子组件-->
            <slot></slot>
        </ul>
    </div>
</template>

<script>
    export default{
        name:'parent',
        data(){
            return{
                items:[],
                heights:1
            }
        },
        props:{
            type:{
                type:Number,
                default:1
            }
        },
        watch:{
            //监听该属性变化
            heights( val,oldval ){
                
//                console.log(val);
//                console.log(oldval);
                
            },
            //只要items有变化 就会执行函数内容
            items(val){
                val.length>0?this.setActive(1123):''
            }
        },
        mounted(){
            //获取所有的子组件对象
            this.items =  this.$children.filter(child=>{
                return child.$options.name =='child'
            });
            this.init()
        },
        methods:{
            init(){
                //调用子组件定义的方法
                this.items[0].says()
            },
            setActive( params ){
                console.log(params)
            }
        }
    }
</script>

<style>
</style>

-------------------------------------------------------   child.vue  -----------------------------------------------------------------------

<template>
    
        <li>
        <!--利用子组件代替img-->
            <slot></slot>
        </li>
    
</template>

<script>
    export default{
        name:'child',
        mounted(){
            
        },
        props:{
            age:{
                default:'你好'
            }
        },
        methods:{
            says(){
                console.log('adc');
                //获取父组件data中的属性
                console.log(this.$parent.items.length)
            }
        }
    }
</script>

<style>
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值