vue作用域插槽详解

vue给我们提供了很方便的父子组件通信方式,父组件通过props向子组件传值,今天我们所要讨论的这个作用域插槽(还不知道什么是作用域插槽的同学请先去看官方文档了解插槽的相关概念),个人觉得就是父子组件传值的反用。我们知道子组件通过props接收来自父组件通过v-bind绑定在子组件标签上传过来的数据,作用域插槽的slot-scope恰恰相反,是父组件接收来自子组件的slot标签上通过v-bind绑定进而传递过来的数据。是不是有点蒙圈,看个例子你就明白啦。


// 父组件
<template>
  <div id="app">
    <child>
      <template slot-scope="a">
        <p v-text="a.item"></p>
      </template>
    </child>
  </div>
</template>

<script>
import child from './child';
export default {
  name: 'app',
  components: {
    child
  }
}
</script>
//子组件
<template>
  <div>
    <ul>
      <li v-for="(item,index) in items" :key="index">{{item}}
        <slot :item='item'></slot>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data () {
    return {
      items:['Webkit','Gecko','Trident','Blink']
    }
  }
}
</script>

我们可以清晰的看到,在子组件中有个插槽slot通过v-bind绑定了一个值item,在父组件中引用了子组件child,child标签里面可以看到作用域插槽template,此时slot-scope就是一个对象,这个对象是由子组件的插槽slot所绑定的值所组成的一个对象,比如在这里slot-scope = {item},这里的item来自子组件,而这里slot-scope的值是a,所以就有了下面的

<p v-text="a.item"></p>

说到这里,想必大家都应该明白了作用域插槽了吧,简单来说就一句话:父组件接收来自子组件的数据。

如果绑定数据太多,而你不需要全都用到的时候可以使用es6的对象解构,关于对象解构比较简单,笔者在此就不再赘述了!

猜你喜欢

转载自blog.csdn.net/weixin_40920953/article/details/80527741