在v-for下使用v-if控制按钮的显示隐藏?

<div  v-for="(item,index) in queryParams.contentList" :key="index">
                <div class="top-title">
                  <div>
                    <el-button @click="handlePopup" type="text">管理</el-button>
                  </div>
                </div>
                <child @watchContentList="(val)=>watchContentList(val,index)" :index="index" :data="item" ref="sourceFrom"/>
              </div>

queryParams.contentList是一个列表v-for渲染显示列表
子组件是一个select组件 watchContentList事件会返回val和index 当val为选择的指定数字的时候列表里的《管理》按钮会隐藏,反之则显示出来
如何控制按钮的显示隐藏

阅读 1k
avatarAI BotBETA

在Vue中,直接使用v-ifv-for在同一个元素上是不推荐的,因为这会导致渲染列表时每次都需要重新计算条件,影响性能。不过,你可以通过在模板中嵌套一个额外的<template>元素或者使用计算属性来预处理数据,从而在v-for中更高效地控制v-if

针对你的场景,你可以通过维护一个额外的数组或对象来跟踪哪些项的“管理”按钮应该被隐藏。这里,我假设你有一个额外的数据属性(例如hiddenButtons)来存储这个信息,它可能是一个数组,其中每个元素对应queryParams.contentList中的一个项的隐藏状态(例如,使用索引作为键)。

以下是一个可能的实现方式:

<template>
  <div v-for="(item, index) in queryParams.contentList" :key="index">
    <div class="top-title">
      <div>
        <!-- 使用v-if来控制按钮的显示隐藏 -->
        <el-button v-if="!hiddenButtons[index]" @click="handlePopup(index)" type="text">管理</el-button>
      </div>
    </div>
    <child 
      @watchContentList="(val, idx) => handleWatchContentList(val, idx)" 
      :index="index" 
      :data="item" 
      ref="sourceFrom"
    />
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryParams: {
        contentList: [], // 假设这是你的列表数据
        // 初始化hiddenButtons,假设与contentList长度相同,初始值全为false
        hiddenButtons: new Array(this.queryParams.contentList.length).fill(false),
      },
    };
  },
  methods: {
    handlePopup(index) {
      // 处理点击事件
      console.log(`Handling popup for index: ${index}`);
    },
    handleWatchContentList(val, idx) {
      // 根据val的值更新hiddenButtons中对应索引的值
      this.hiddenButtons[idx] = val === 你的指定数字; // 替换'你的指定数字'为实际的条件值
    },
  },
};
</script>

注意,这里handleWatchContentList方法接收validx(或index)作为参数,并据此更新hiddenButtons数组。你需要将子组件中触发的watchContentList事件的参数修改为同时发送值和索引,或者根据你的实际情况调整这部分逻辑。

另外,请确保在组件的data函数中正确初始化hiddenButtons数组,其长度应与queryParams.contentList一致,并且初始值全部为false(或根据你的需求设置)。这样,你就可以在v-for循环中使用v-if="!hiddenButtons[index]"来控制“管理”按钮的显示隐藏了。

2 个回答

首先管理按钮和child都是循环出来的,所以管理按钮的显示隐藏状态应该是一个数组,那么可以在给queryParams.contentList赋值之前添加一个字段,用来控制button的显示隐藏,或者也可以新增一个queryParams.contentList.length长度的数组,用数组中的每一项,来控制button的显示隐藏;最后在watchContentList方法中,根据index去修改queryParams.contentList的属性或新增数组的状态。

帮你写好了。

<script step>
let v = ref('')

function watchContentList(val,index){
    v.value = val;
}

</script>

<template>
<div  v-for="(item,index) in queryParams.contentList" :key="index">
  <div class="top-title">
    <div>
      <el-button @click="handlePopup" type="text" v-if="v">管理</el-button>
    </div>
  </div>
  <child @watchContentList="(val)=>watchContentList(val,index)" :index="index" :data="item" ref="sourceFrom"/>
</div>
</template>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题