作用域插槽

99 阅读1分钟
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>

<body>
    <div id="demo">
        <field-assemly>
                            <!-- slot 对应子组件的name   slot-scope="props" 定义的临时变量名-->
                <template slot="field" slot-scope="props">
                            <!-- text 是子组件slot中要获取的内容 props则是临时变量 -->
                        {{props.text}}
                        {{props.ss}}

                    </template>
        </field-assemly>
    </div>

    <script>
        Vue.component('field-assemly',{
                                    // DOM通过slot中的name来获取数据
                template:'<div>\
                              <slot text="子组件内容" ss="我是ss" name="field">\
                              </slot>\
                          </div>'
        })
        var app = new Vue({
            el: '#demo',
            data: {
            }
        }) 
    </script>
</body>

</html>