天天看点

Vue插槽的理解什么是插槽?

什么是插槽?

插槽就是子组件中的提供给父组件使用的一个占位符,用<slot></slot> 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的<slot></slot>标签。举个例子:

1、先看一下下面的代码,声明一个child-component组件,如果现在我想在<child-component></child-component>内放置一些内容,结果会是怎样?

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>插槽</title>
    <script src="../vue.min.js"></script>
</head>
<body>
<div id="app">
    <div>使用slot分发内容</div>
    <div>
        <child-component>
            <div>多云,最高气温34度,最低气温28度,微风</div>
        </child-component>
    </div>
</div>

<script>
    Vue.component('child-component', {
        template: '<div>' +
            '<h1>今天天气状况:</h1>' +
            '</div>'
    });
    var app = new Vue({
        el: '#app'
    });
</script>
</body>
</html>
           

显示效果:输出内容还是在组件中的内容,在 <child-component>内写的内容没起作用。

Vue插槽的理解什么是插槽?

2、我们现在给组件增加一个<slot></slot>插槽,则就起作用了

<script>
    Vue.component('child-component', {
        template: '<div>' +
            '<h1>今天天气状况:</h1>' +
            '<slot></slot>' +
            '</div>'
    });
    var app = new Vue({
        el: '#app'
    });
</script>
           
Vue插槽的理解什么是插槽?

参考:

https://www.cnblogs.com/mandy-dyf/p/11528505.html