首页 > 解决方案 > v-if 在 v-for 中显示一个部分

问题描述

我正在尝试做类似linkedin评论的事情,虽然页面上显示了多个帖子,但如果您单击该帖子的“显示评论”,则只会显示该帖子评论。

我的解决方案:在 created() 中创建 162 个布尔变量,然后使用 v-for 中的索引写我的 v-if 但它不会打开我想要的 div。当我将变量设为 true 时,必须在 created() 中提及全部打开。我们只显示 162 个帖子!

当它为假时,单击它们的值更改为真后(用console.log检查)但div不会打开!

<template>
  <span v-if="post.comments_status == 1" class="optiontext cursor-pointer" @click="showcomment(index)"><i
            class="fa fa-comment-o"></i> OPEN COMMENT SECTION FOR THIS POST 
  </span>

<div class="col-md-8" id="imtop" style="direction:rtl">

    <!-- v-if part to show comments-->
    <div v-if="Commenton[index] == true" class="col-md-12 commentsec">
        <div class="eachcomment col-md-12">
            <div class="usercomment">
                <img :src="images" class="pop-img-min"/>
            </div><!-- usercomment end-->
        </div>

    </div><!-- end of allposts-->
</div>
</template>

<script>
  import vSelect from 'vue-select'
  import axios from 'axios'
  export default {

  components: {vSelect},
  props: ['alltags','posts'],
  data() {
    return {
      searchoptions:[{label:'جدیدترین ',value:'newest'},{label:'محبوبترین',value:'محبوبترین'}],
      Commenton:[],
    }
  },

  created() {
    for(var i = 0; i<162;i++) {
      this.Commenton[i] = false;
    }

  },
  mounted() {
    this.getInitialUsers();
    this.scroll(this.post);
  },
  methods: {
    showcomment(indexof){
      if(this.Commenton[indexof] == false){
        this.Commenton[indexof]=true;
      }else if(this.Commenton == true) {
        this.Commenton=false;
      }
    },

  },

}


</script>

注意:它是一个包含超过 1000 行代码的单页 web 应用程序,必须删除很多部分,因此您可能会看到额外的 div 标签或其他东西,但程序运行正常。

我的后端是 laravel,但我认为这与此无关!

谢谢你的帮助

标签: javascriptvue.jsvuejs2

解决方案


你有反应问题。

这些问题是由于 Javascript 环境的限制,vue 无法检测到数组修改造成的。要确保 vue 看到您的更改,请使用this.$set(object, key, value)

// Inside your created method:
this.$set(this.Commenton, i, false);

// inside you showComment method
    showcomment(indexof){

        if(this.Commenton[indexof] == false){
            this.$set(this.Commenton, indexof, true);
        }else if(this.Commenton[indexof] == true) {
            this.$set(this.Commenton, indexof, false);
        }


   },

推荐阅读