vue插槽

233 阅读2分钟

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>vue中插槽的使用</title>
    <style>

    </style>

    <script src="./lib/vue-2.4.0.js">

    </script>
</head>
<body>
    <div id="app">
        <child>
            <div>dfsdfgsdgsdg</div>
            <p>dsfsdgsdg</p>
        </child>
    </div>
    <script>
        Vue.component('child', {
            props: {
                content: {
                    type: String
                }
            },
            template: `<div>
                     <p>helloworld</p>
                     <slot></slot>      
                  </div>`

        })
        var vm = new Vue({
            el: '#app',
        })
    </script>
</body>

</html>

2默认内容

<!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>vue中插槽的使用</title>
    <style>

    </style>

    <script src="./lib/vue-2.4.0.js">

    </script>
</head>
<body>
    <div id="app">
        <child>
            <!-- <div>dfsdfgsdgsdg</div>
            <p>dsfsdgsdg</p> -->
        </child>
    </div>
    <script>
        Vue.component('child', {
            props: {
                content: {
                    type: String
                }
            },
            template: `<div>
                     <p>helloworld</p>
                     <slot>覅深水电费感受到</slot>      
                  </div>`

        })
        var vm = new Vue({
            el: '#app',
        })
    </script>
</body>

</html>

3 具名插槽

<!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>vue中插槽的使用</title>
    <style>

    </style>

    <script src="./lib/vue-2.4.0.js">

    </script>
</head>
<body>
    <div id="app">
        <child>
            <div class="header" slot='header'>头部</div>
            <div class="footer" slot='footer'>底部</div>
        </child>
    </div>
    <script>
        Vue.component('child', {
            props: {
                content: {
                    type: String
                }
            },
            template: `<div>
                    //如果没有传具名插槽 就显示默认值
                     <slot name='header'>默认值</slot>   
                     <p>helloworld</p>
                     <slot name='footer'></slot>      
                  </div>`

        })
        var vm = new Vue({
            el: '#app',
        })
    </script>
</body>

</html>  

4 作用域插槽