详解Vue.js分发之作用域槽

首先,需要知道的是,每个组件有每个组件自己的作用域。每个组件都是Vue()的实例,有自己的作用域。

比如现在有个组件这样的:

Vue.component('father-component1',{ template:'<div><p>Hi,我是父组件</p>{{fatherMessage}}</div>', data:function(){ return { fatherMessage:'这是父组件发出的消息哦~' } }, });

这个data只为template里的模板服务。同样的,子组件的data只为子组件的模板服务。因为他们都是各自作用域内的属性。

在slot分发中,无论是单分发还是具名分发,都是父组件替换子组件的数据,或者没有替换,用子组件默认的数据。两者并不能共存。这样他们就没有数据联系了。

但是通过设置作用域槽,就可以改变这种状况,让子组件可以在父组件进行分发时获取自己的数据,至于是什么数据,由子组件决定,这样就能解耦了。

作用域槽通过slot的一个自定义的属性,官方给出的DEMO是text,但也可以是其他,值为暴露的数据。

这个自定义属性已经存放在子组件的prop对象里了。等待着被父组件获取。

怎么获取呢?

在父组件的模板里,使用一个Vue自带的特殊组件<template> ,并在该组件上使用scope属性,值是一个临时的变量,存着的是由子组件传过来的prop对象,在下面的例子中我把他命名为props。

获得由子传过来的prop对象。这时候,父组件就可以访问子组件在自定义属性上暴露的数据了。

//js Vue.component('child-component4',{ template:'<ul>' + '<slot v-for="item in fruit" v-bind:text="item.name">?</slot>' + '</ul>', data:function(){ return { fruit:[ {name:'苹果'}, {name:'香蕉'}, {name:'橙子'} ] } }, }); Vue.component('father-component4',{ template:'<child-component4>' + '<template scope="props" slot="child-ul">' + '<li >{{props.text}}</li>' + '</template>' + '</child-component4>' }); var app16 = new Vue({ el:'#app16' }); <div> <father-component4></father-component4> </div>

以上的的组件组合会被渲染为:

<div> <ul> <li>苹果</li> <li>香蕉</li> <li>橙子</li> </ul> </div>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyxzsw.html