vue-插槽(slot)

插槽其实是为了维护的负担,就相当于,把每一块的内容给模块化。使用的是 标签实现的


执行过程:首先自定义三个组件,名字分别是todo、todo-title、todo-items,然后在todo这里边,通过使用slot标签的name来绑定这个组件,然后在id为app的div里边使用 slot绑定这个标签,至此这个才算是把它们全部绑定起来了。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>插槽</title>
</head>
<body>

    <div id="app">
        <todo>
            <!--v-bind:title="title"等价于 :title="title"-->
            <todo-title slot="todo-title" v-bind:title="title"></todo-title>
            <todo-items slot="todo-items" v-for="item in items" :item="item"></todo-items>
        </todo>
    </div>

    <!--引入vue的cdn-->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script>
        Vue.component("todo",{
      
      
            template: "<div>\
                            <slot name='todo-title'></slot>\
                            <ul>\
                                <slot name='todo-items'></slot>\
                            </ul>\
                        </div>"
        });

        Vue.component("todo-title",{
      
      
            props: ["title"],
            template: "<div>{
      
      {title}}</div>"
        });

        Vue.component("todo-items",{
      
      
            props: ["item"],
            template: "<li>{
      
      {item}}</li>"
        });

        var vm = new Vue({
      
      
            el: "#app",
            data: {
      
      
                title: "四大名著",
                items: ["红楼梦","西游记","三国演义","水浒传"]
            }
        });
    </script>

</body>
</html>

结果如下

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/fgets__/article/details/121539048