作用域插槽理解

来源:互联网 发布:长沙seo团队 编辑:程序博客网 时间:2024/05/22 10:31

        早上5点下大雨了,迷迷糊糊起来收衣服,一不小心踩滑了,脑袋重重的摔在床上,嘤嘤嘤,瞬间蒙蔽到无法呼吸,大概是抬头45°仰望天空的时候姿势不对,总是感觉黑盒子里的知识洒了一些,白天笨笨的,晚上回家的时候好好找一下滴落的智慧。

        本篇讲一下作用域插槽的理解,本汪认为是子组件与父组件的数据动态交互的一种常见案例,二话不说先上代码:

html:

<div id="app" class="parent">  <child>    <template scope="a">      <span>hello from parent</span>      <span>{{ a.say }}</span>    </template>  </child></div>
父组件中必须要有template元素,且必须有scope特性,scope特性中是临时变量名,接收从子组件中传递上来的属性,属性可以是任意定义的。

js:

<script type="text/javascript">Vue.component('child',{template:'\<div class="child">\  <slot say="hello from child"></slot>\</div>'});new Vue({el:"#app"})</script>


下面再上一个列表组建的demo,在这个demo中本汪特意打乱了属性的名字,为了明确数据之间的关系,(在阅读vue官方文档的时候给出的demo简洁漂亮,但是一本正经的变量命名容易让人迷惑),希望读者自行品读其中的数据关联关系,大笑

html:

<div id="app">        <girl :favorite-a="items">           <template slot="cute" scope="variable"> <!-- /*作用域插槽也是可以具名的*/ -->                <li style="padding:8px 2px;">{{variable.thing}}</li><!-- scope变量调用的值必须和slot传出的值保持一致 -->            </template>        </girl>    </div>    <script>    Vue.component('girl',{        template:'\        <ul>\            <slot name="cute" \                  v-for="dos in favoriteA" \                  :thing = "dos.what" >\            </slot>\        </ul>\        ',        props:['favorite-a']//数据是从外部传进来的  所以需要props动态接收        //父组件动态绑定的属性要和props中的属性的写法保持一致,但是在slot中计算时要还原成驼峰形式    })    new Vue({        el:"#app",        data:{            items:[                {what:'逛'},                {what:'吃'},                {what:'打扮'},                {what:'逛'},                {what:'吃'},                {what:'打扮'},                {what:'逛'},                {what:'吃'},                {what:'打扮'}            ]        }    })    </script>

注释点已在代码中标出,就不再赘述啦哈哈哈,拜拜哒,放学咯。


哈哈哈 ,  打架吧狗子君。