VUE 模板怎样复用?

ZeronoFreya
  • 271
<ul class="panel">
    <li class="action_list action_expanded">
        <MenuStatus/>
    </li>
    <li class="action_list"
        :class="{'action_expanded': 1 == secActive}">
        <div class="toggle"
            @click.prevent.stop="toggleSecMenu(1, $event)">
            <span class="action_name">Apparent Horizon</span>
        </div>
        <MenuApparentHorizon/>
    </li>
    <li class="action_list"
        :class="{'action_expanded': 2 == secActive}">
        <div class="toggle"
            @click.prevent.stop="toggleSecMenu(2, $event)">
            <span class="action_name">Material</span>
        </div>
        <MenuMaterial/>
    </li>
    <li class="action_list"
        :class="{'action_expanded': 3 == secActive}">
        <div class="toggle"
            @click.prevent.stop="toggleSecMenu(3, $event)">
            <span class="action_name">Camera</span>
        </div>
        <MenuPerspective/>
    </li>
</ul>

如上代码, 重复性很高,请问该怎么优化呢?

最开始写的

<template v-for="(item, index) in items">
  <li class="action_list"
      :class="{'action_expanded': index == secActive || !item.text}"
      v-if="item.template">
      <div v-if="item.text" class="toggle"
          @click.prevent.stop="toggleSecMenu(index, $event)">
          <span class="action_name">{{ item.text }}</span>
      </div>
      <component @closeMenu="closeMenu" :is="item.template"></component>
  </li>
  <li class="action_list" v-else @click.prevent.stop="item.action">{{ item.text }}</li>
</template>


items: [
    {
        template: MenuStatus
    },
    {
        text: "Apparent Horizon",
        template: MenuApparentHorizon
    },
    {
        text: "Material",
        template: MenuMaterial
    },
    {
        text: "Camera",
        template: MenuPerspective
    }
]

感觉太复杂了,不利于后续修改

回复
阅读 5.2k
1 个回答

创建一个html文件,其他组件引用这个文件作为模版,其实也就是一个字符串的多次引用

宣传栏