首页 > 其他 > 详细

使用render渲染的便利之处

时间:2021-08-10 23:24:13      阅读:19      评论:0      收藏:0      [点我收藏+]

定义一个Title组件,在使用的时候,通过父组件传值level去定义这个title是h1~h6

 

1、components/Title.vue:

<template>
  <h1 v-if="level===1">
    <a href="">
      <slot></slot>
    </a>
  </h1>
  <h2 v-else-if="level===2">
    <a href="">
      <slot></slot>
    </a>
  </h2>
  <h3 v-else-if="level===3">
    <a href="">
      <slot></slot>
    </a>
  </h3>
  <h4 v-else-if="level===4">
    <a href="">
      <slot></slot>
    </a>
  </h4>
  <h5 v-else-if="level===5">
    <a href="">
      <slot></slot>
    </a>
  </h5>
  <h6 v-else-if="level===6">
    <a href="">
      <slot></slot>
    </a>
  </h6>
</template>
<script>
export default {
  props: [level]
}
</script>

2、使用

<template>
  <div id="app">
    <Title :level=‘1‘>标题一</Title>
    <Title :level=‘2‘>标题二</Title>
    <Title :level=‘3‘>标题三</Title>
    <Title :level=‘4‘>标题四</Title>
    <Title :level=‘5‘>标题五</Title>
    <Title :level=‘6‘>标题六</Title>
  </div>
</template>
<script>
import Title from @/components/Title
export default {
  components: { Title }
}
</script>

 

 

可以发现,在定义Title组件时使用了大量的if、if-else,这里可以使用render进行渲染,代码会变得简洁

components/title.js:

export default {
  props: [‘level‘],
  render(h) {
    const tag = ‘h‘ + this.level
    return <tag><a href=‘‘>{this.$slots.default}</a></tag>
  }
}

 

使用render渲染的便利之处

原文:https://www.cnblogs.com/wuqilang/p/15125999.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!