$scopedSlots的一点用法

590 阅读1分钟

例子1

Test.vue
<script>
export default {
  props: {
    data: {
      type: Array,
      default() {
        return []
      }
    }
  },
  render(h, vm) {
    return (
      <ul>
        {this.data.map(item => (
          <li>
            {this.$scopedSlots.default(item)}
          </li>
        ))}
      </ul>
    )
  }
}
</script>

导入测试

  <test :data="data">
   <span slot-scope="scope">{{scope.name}} | vm.$slots的使用</span>
  </test>
</template>

<script>
import Test from './test.vue'
export default {
  components: {
    Test
  },

  data() {
    return {
      data: [
        { name: 111 },
        { name: 222 },
        { name: 333 }
      ]
    }
  }
}
</script>

1.jpg

例子2

test2.vue
<script>
export default {
  render(h) {
    return h('div', [this.$scopedSlots.default({
      text: '111caomingrui'
    }),
    this.$scopedSlots.name1({
      text: '222hello scope'
    })
    ])
  },
  mounted() {
    this.log()
  },
  methods: {
    log(res) {
      console.log(this.$slots)
      console.log(this.$scopedSlots)
    },
  },
}
</script>

导入测试

  <Test2>
    <div slot-scope="props">{{ props.text }}</div>
    <template slot="name1" scope="props">
      <span>{{props.text}}</span>
    </template>
  </Test2>
</template>

<script>
import Test2 from './test2.vue'
export default {
  components: {
    Test2
  },
}
</script>

2.jpg