Vue 插槽

组件内部定义 slot name=“插槽名”

外部使用 template

template 标签属性slot=“插槽名” 或者 #插槽名

作用域插槽

使用作用域插槽可以操作通过props传递过去的数据

外部可用 template 标签属性slot-scope=“数据别名(任意)”
template标签内使用插值表达式或v-text指令
数据别名.属性名 获取数据

比如:组件内

<li v-for="item in list">
   <slot :info='item'></slot>
</li>

组件外

<template slot-scope="scope">
    <strong>{{scope.info.name}}</strong>
</template>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<body>
    <div id="components-demo">
        <button-counter :list="mylist">
            <template #title>
                <h1>标题</h1>
            </template>
            <template slot-scope="scope">
                <strong>{{scope.info.name}}</strong>
            </template>
        </button-counter>
    </div>
</body>
<script>
    // 提供事件中心
    var eventBus=new Vue();

    // 定义一个名为 button-counter 的新组件
    Vue.component('button-counter', {
    props:['list'],
    template: `
        <div>
            <slot name="title"></slot>
            <ul>
                <li v-for="item in list">
                    <slot :info='item'></slot>
                </li>
            </ul>    
        </div>
        `,
    methods:{
        handle(){
            eventBus.$emit('add2',1)
        }
    },
    mounted(){
        eventBus.$on('add',(val)=>{
            this.count+=val
        })
    },
    })

    var app=new Vue({
        el:'#components-demo',
            data(){
                return {
                    mylist:[
                        {id:1,name:"苹果"},
                        {id:2,name:"香蕉"},
                        {id:3,name:"橘子"}
                    ]
                }
            }
        })
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值