vue3.2 admin 渲染 html

596 阅读1分钟

看 vue2 的某个admin 代码

export default {
  name: 'MenuItem',
  functional: true,
  props: {
    icon: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    }
  },
  render(h, context) {
    const { icon, title } = context.props
    const vnodes = []

    if (icon) {
      if (icon.includes('el-icon')) {
        vnodes.push(<i class={[icon, 'sub-el-icon']} />)
      } else {
        vnodes.push(<svg-icon icon-class={icon}/>)
      }
    }

    if (title) {
      vnodes.push(<span slot='title'>{(title)}</span>)
    }
    return vnodes
  }
}

vue3 实现

h 函数使用

<script lang="ts">
import { h } from 'vue'
export default {
  name: 'MenuItem',
  props: {
    icon: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    }
  },
  setup(props, { slots, attrs, emit }) {
    const vnodes = []
    if (props.icon) {
      // console.log('props.title', props.title);
      if (props.icon.includes('el-icon')) {
        vnodes.push(h('i', { class: [props.icon, 'sub-el-icon'] }))
      } else {
        // vnodes.push(h('svg-icon', { 'icon-class': props.icon }))
        vnodes.push(h('el-icon', { 'icon-class': props.icon }))
      }
    }
    if (props.title) {
      vnodes.push(h('span', { slot: 'title' }, props.title))
    }

    return ()=>{
      return vnodes
    }
  }
}
</script>

总结

  • 虽然 setup 代码很方便,但是有些代码还是需要用 vue2 方法写
  • 新技术有时候会卡住, 用老方法先跳过是个捷径