vue-插槽作用域的使用

  父组件想要在自个的模板中使用子组件的data数据,有3种方式:

  1. 子组件发送事件:主动方是子组件

  2. 父组件获取子组件的对象,通过this.childredn或refs,但这种方式大多是用在scirpt代码里面,在template模板中并不适用

  3. 插槽作用域的方式获取,该方式能在template模板中来获取子组件的data数据,主要也是为了讲这个

  直接解释会比较麻烦,先看代码在解释:

<body>
  <div id="app">
    <ccomponent>
      <template slot-scope="slot">
        <h1>{{slot.data}}</h1>
      </template>
    </ccomponent>
  </div>

</body>
<template id="tem">
  <div>
    <slot :data="books"></slot>
  </div>
</template>

<script>
    const ccomponent = {
      data(){
        return {
          books: ['刘沉香舅母','宝莲灯爆了','谁动了我的宝莲洞']
        }
      },
      //data,props,methods,template,component
      template: '#tem'
    }
    var vm = new Vue({
      el: '#app',
      data: {},
      methods: {},
      components: {
        ccomponent
      }
    });
</script>

  大概的步骤是这样的:

    1. 在子组件的slot标签定义一个属性(属性名任意),为该属性绑定子组件中的data数据

    2. 在父组件的template中使用子组件并添加插槽时,一定要被<template>标签所包含,并设置slot-scope属性,slot-scope属性值代表 slot标签,接着获取他slot的属性即可拿到数据

  注意:在vue2.5以下一定得使用<template>,2.5以后可使用任意标签。

posted @ 2021-03-26 15:18  爱编程DE文兄  阅读(228)  评论(0编辑  收藏  举报