Vue:插槽的基本使用方法以及案例分析

1.组件插槽的作用

在这里插入图片描述
2.插槽使用方法:

在这里插入图片描述
slot的作用:预留一个插槽用于传递数据 小细节:如果slot里面有值,且父级模板中也有值, slot里面的值会被覆盖

案例:(分析看注释)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./js/vue.js"></script>
    <title>Document</title>
</head>

<body>
    <div id="app">
        <example-test :colorstyle="colorStyle">出现一个bug</example-test>
    </div>
    <script>
        //插槽的作用:父组件想子组件传递内容
        Vue.component('example-test', {
            props: ['colorstyle'],
            template: `
            <div>
                <strong :style="{color:colorstyle}">ERROR:</strong>
                <!--我利用props属性传递父组件模板的数据到子组件模板,实现动态更改style里面的值-->
                <slot></slot>
                <!--预留一个插槽用于传递数据 小细节:如果slot里面有值,且父级模板中也有值 slot里面的值会被覆盖-->
                </div>
            `,
        })
        var vm = new Vue({
            el: '#app',
            data: {
                colorStyle: 'red'
            },
        })
    </script>
</body>

</html>

运行结果:
在这里插入图片描述

发布了28 篇原创文章 · 获赞 7 · 访问量 1182

猜你喜欢

转载自blog.csdn.net/haduwi/article/details/105171115
今日推荐