zoukankan      html  css  js  c++  java
  • 使用render渲染的便利之处

    定义一个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>
      }
    }
  • 相关阅读:
    vue 启动报错:`TypeError: Cannot read property 'range' of null`
    手动创建自己的npm包
    uni-app 拦截页面传参
    uni-app的vue.config.js
    插入排序
    选择排序
    设计模式--享元模式
    设计模式--代理模式
    原型链图片
    深度优先遍历和广度优先遍历
  • 原文地址:https://www.cnblogs.com/wuqilang/p/15125999.html
Copyright © 2011-2022 走看看