Vue render函数 函数时组件 jsx

常规组件使用

定义组件

components/list/list.vue

<template>
  <ul>
    <li v-for="(item, index) in list" :key="`item_${index}`">
      {{ item.name }}
    </li>
  </ul>
</template>
<script>
export default {
  name: 'List',
  props: {
    list: {
      type: Array,
      default: () => []
    }
  }
}
</script>

components/list/index.js

import list from './list'
export default list

组件使用

views/render-page.vue


<template>
  <div>
    <list :list=list></list>
  </div>
</template>
<script>
import List from '_c/list'
export default {
  data () {
    return {
      list: [
        { name: 'name1' },
        { name: 'name2' }
      ]
    }
  },
  components: {
    List
  }
}
</script>

效果图:
效果图:

定义函数式组件

components/render-dom.vue

export default {
  function: true,
  props: {
    name: String,
    renderFunc: Function
  },
  render: (h, ctx) => {
    return ctx.props.renderFunc(h, ctx.props.name)
  }
}

使用函数式组件

components/list/list.vue

<template>
  <ul>
    <li v-for="(item, index) in list" :key="`item_${index}`">
      <span v-if="!render">{{ item.name }}</span>
      <render-dom v-else :render-func="render" :name="item.name"></render-dom>
    </li>
  </ul>
</template>
<script>
import RenderDom from '_c/render-dom'
export default {
  name: 'List',
  components: {
    RenderDom
  },
  props: {
    list: {
      type: Array,
      default: () => []
    },
    render: {
      type: Function,
      default: () => {}
    }
  }
}
</script>

views/render-page.vue

<template>
  <div>
    <list :list=list :render="renderFunc"></list>
  </div>
</template>
<script>
import List from '_c/list'
export default {
  data () {
    return {
      list: [
        { name: 'name1' },
        { name: 'name2' }
      ]
    }
  },
  components: {
    List
  },
  methods: {
    renderFunc (h, name) {
      return h('i', {
        style: {
          color: 'green'
        }
      }, name)
    }
  }
}
</script>

效果图:
效果图:
其余文件如函数式组件

views/render-page.vue

<template>
  <div>
    <list :list=list :render="renderFunc"></list>
  </div>
</template>
<script>
import List from '_c/list'
export default {
  data () {
    return {
      list: [
        { name: 'name1' },
        { name: 'name2' }
      ]
    }
  },
  components: {
    List
  },
  methods: {
    renderFunc (h, name) {
      return (
        <i on-click={this.handleClick} style={{ color: 'blue' }}>{name}</i>
      )
    },
    handleClick (e) {
      console.log(e)
    }
  }
}
</script>

效果图:
在这里插入图片描述

posted @ 2019-06-01 14:28  仲灏  阅读(763)  评论(4编辑  收藏  举报