vant 多个Popover

2,350 阅读1分钟

去支援的有个项目用的vant,需要在v-for中有多个Popover。我本身vue不熟,搜相关文档也没走通,最后按着文档整了一个不怎么美好的可行的解决方案(主要是刚做完pm把这个功能砍掉了,我一定要放出来,不然半天白干了 5555~),有缘看到的同学有好的解决方案 一定拜托慷慨的评论吧

<div class="diagnosis-item" v-for="(k, i) in item.diagnosis" :key="i">
  <div class="sub-title">
    // ...省略一些无关的
    <div
      v-if="k.questionDesc && (tabActive === 0 || tabActive === 1)"
      class="diagnosis-popover"
      :id="'popover-' + tabActive + '-' + i"
      @click.stop="changeExtraDesc(i)" // 要阻止冒泡
    >
    </div>
    <van-popover
      v-if="k.questionDesc && tabActive === 0"
      v-model="popoverVisable_0"
      trigger="click"
      placement="bottom"
      :get-container="getContainer" // 绑定指定节点
    >
      <template #reference>
        <van-icon name="question-o" />
      </template>
      <div class="diagnosis-popover-content">
        {{ k.questionDesc }}
      </div>
    </van-popover>
    <van-popover
      v-if="k.questionDesc && tabActive === 1"
      v-model="popoverVisable_1"
      trigger="click"
      placement="bottom"
      :get-container="getContainer"
    >
     <template #reference>
        <van-icon name="question-o" />
      </template>
      <div class="diagnosis-popover-content">
        {{ k.questionDesc }}
      </div>
    </van-popover>
  </div>
  // ...省略一些无关的
</div>

data中

data() {
 return {
  popoverVisable_0: false,
  popoverVisable_1: false,
  tabActive: 0,
  tabActiveSubIndex: 0,
  };
},

methods

changeExtraDesc(index) {
  this.tabActiveSubIndex = index;
  this.popoverVisable_0 = !this.popoverVisable_0;
  this.popoverVisable_1 = !this.popoverVisable_1;
},
getContainer() {
  // 保证节点唯一
  const tar = `#popover-${this.tabActive}-${this.tabActiveSubIndex}`;
  return document.querySelector(tar);
},