一例完全理解vue 2.0 的slots 和 functional render

https://jsfiddle.net/pronan/mjqpmw0u/
通过调节plan="bbb"的值, 比如换成plan="children",你会发现ctx.slots()ctx.children是怎样和ttt的子节点对应的.

<!DOCTYPE html>
<html lang='zh'>
<head>
  <title></title> 
</head>
<body>
  <div id="app">
    <ttt plan="bbb">
      <aaa></aaa>
      <bbb slot="bbb" msg="slot-1"></bbb>
      <p>default-1</p>
      <bbb slot="bbb" msg="slot-2"></bbb>
      <ccc slot="ccc"></ccc>
      <p>default-2</p>
    </ttt>
  </div>
<script src="https://cdn.staticfile.org/vue/2.3.2/vue.js"></script>
<script>
Vue.component('aaa', {
  functional: true,
  render: function (h, ctx) {
    return h('div',['aaa'])
  },
})
Vue.component('bbb', {
  functional: true,
  render: function (h, ctx) {
    return h('div',['bbb:'+ctx.props.msg])
  },
})
Vue.component('ccc', {
  functional: true,
  render: function (h, ctx) {
    return h('div',['ccc'])
  },
})
Vue.component('ttt', {
  functional: true,
  render: function (h, ctx) {
    console.log(ctx.children)
    console.log(ctx.slots())
    var plan = ctx.props.plan
    var slots = ctx.slots()
    var children
    if (plan == 'children') {
      children = ctx.children
    } else if (plan == 'bbb') {
      children = slots.bbb
    } else if (plan == 'ccc') {
      children = slots.ccc
    } else {
      children = slots.default
    }
    return h('div',children)
  },
})
var app = new Vue({
}).$mount('#app')
</script>
</body>
</html>
posted @ 2017-05-25 23:30  LisPythoniC  阅读(696)  评论(0编辑  收藏  举报