这里有新鲜出炉的 vue.js 教程,程序狗速度看过来!
Vue.js 是构建 web 界面的 JavaScript 库,提供数据驱动的组件,还有简单灵活的 API,使得 MVVM 更简单。
本篇文章主要介绍了详解 Vue.js 分发之作用域槽,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
首先,需要知道的是,每个组件有每个组件自己的作用域。每个组件都是 Vue() 的实例,有自己的作用域。
比如现在有个组件这样的:
- Vue.component('father-component1', {
- template: '<div class="father"><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 name="child-ul" 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 class="child-li" >{{props.text}}</li>' +
- '</template>' +
- '</child-component4>'
- });
- var app16 = new Vue({
- el:'#app16'
- });
- <div id="app16">
- <father-component4></father-component4>
- </div>
以上的的组件组合会被渲染为:
- <div id="app16">
- <ul>
- <li class="child-li">苹果</li>
- <li class="child-li">香蕉</li>
- <li class="child-li">橙子</li>
- </ul>
- </div>
来源: http://www.phperz.com/article/17/0814/338688.html