新手关于 Vue Slot 的理解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wyk304443164/article/details/77836450

本文出自:

http://blog.csdn.net/wyk304443164

看了Vue两天了,记了不少笔记。基本都是稍微看了下,等项目的时候再搞吧。


下面开始

说实话官网比较难懂,在我一开始看的时候,很懵逼,然后看了这篇

http://blog.csdn.net/sinat_17775997/article/details/52484072

讲的真的很好。我都能看懂……(^ ^)

下面来点个人总结:

单个Slot

在children这个标签里面放Dom,Vue不会理你,也就是不会显示,类似React:this.props.children。

//父
<children>  
    <span>12345</span>//这边不会显示
</children>

//子
components: {
    children: {
        template: "<button>为了明确作用范围,所以使用button标签</button>"
    }
}

你需要写成这样

children: {
    template: "<button><slot></slot>为了明确作用范围,所以使用button标签</button>"  
} 

注意这边 slot 相当于一个坑,等着父组件给填上,这边 slot 代表的就是上面的 span

多个Slot

这边需要加name属性,说白了,多个Slot就不像上面单个,需要有个对应关系。

父-> slot="name1"
子-> <slot name="name1"
//父
<children>  
    <span slot="name1">12345</span>
</children>

//子
components: {
    children: {
        template: "<button>
                        <slot name="name1"></slot>
                        button标签
                    </button>"
    }
}

这边写了一个name1,如果有多个,就插多个,比较简单。

作用域

<children>  
    <span slot="first" @click="tobeknow">
     12345
    </span>  
    <span slot="second">56789</span> 
</children>

这边的@click=”tobeknow”的作用域是 父组件,也就是,不能访问自组件的方法

父组件模板的内容在父组件作用域内编译;子组件模板的内容在子组件作用域内编译

没有分发时内容的提示

如果父组件与自组件有对应的name。
那么父组件优先,<slot>xx</slot>,xx不会显示

如果没有对应的name
那么子组件内的<slot>xxx</slot>,xxx 将会被展开,<slot>标签被删除。
<div id="app">  
    <children>  
        <span slot="first">【12345】</span>  
        <!--上面这行不会显示-->  
    </children>  
</div>  
<script>  
    var vm = new Vue({  
        el: '#app',  
        components: {  
            children: {
                template: "<div><slot name='first'><button>【如果没有内容则显示我1】</button></slot>为了明确作用范围,<slot name='last'><button>【如果没有内容则显示我2】</button></slot>所以使用button标签</div>"  
            }  
        }  
    });  
</script>
说明:
【1name='first'的slot标签被父组件对应的标签所替换(slot标签内部的内容被舍弃);
【2name='last'的slot标签,因为没有对应的内容,则显示该slot标签内部的内容。

父组件控制子组件内部的方法

this.$children[0].tohidden = true;
<div id="app">  
    <button @click="toshow">点击让子组件显示</button>  
    <children v-if="abc">  
    </children>  
</div>  
<script>  
    var vm = new Vue({  
        el: '#app',  
        data: {  
            abc: false  
        },  
        methods: {  
            toshow: function () {  
                this.abc = !this.abc;  
            }  
        },  
        components: {  
            children: {
                template: "<div>这里是子组件</div>"  
            }  
        }  
    });  
</script>  

猜你喜欢

转载自blog.csdn.net/wyk304443164/article/details/77836450