封装组件时,条件渲染

106 阅读1分钟

封装组件时,需要根据条件判断渲染哪些代码片段,首先想到的是使用template组件,但是想直接渲染,不想外边再有一层根元素,这是需要安装vue-fragment

1、安装 npm install vue-fragment -S

2、注册 import Fragment from 'vue-fragment' Vue.use(Fragment.Plugin)

3、使用

  <template>
    <fragment>
      <template v-if="true">
        <div>1</div>
      </template>
      <template v-else>
        <div>2</div>
      </template>
    </fragment>
  </template>
  /**
   *渲染结果
   *<div>1</div>
  */