Home > Enterprise >  Vue.js 2.6.11. How to hide all li elements except one on click during loop?
Vue.js 2.6.11. How to hide all li elements except one on click during loop?

Time:07-11

For a general understanding of the essence of the issue, I will attach screenshots from the layout.

static layout

layout when question was clicked

Have questions. They will be output through the loop. The loop consists of what will be inside the li tag. When you click on the button, the content inside should open and this question should be removed.

But the problem is that other questions are displayed in the loop that are not related to the click.

How can I make it so that when clicked, the content inside the clicked question is opened and other questions are hidden?

Perhaps there are specific tools in vue. Or is it all done at the html level. I will be glad for any help!

I will insert a piece of code from this component so that there is an understanding of the issue.

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<li v-for="question in questions" :key="question.id" : >
                <button :id="question.id" v-bind: v-on:click="showQuestion(question, $event)" type="button">
                  {{question.title}}
                </button>
                <div v-bind: >
                  <div >
                    <h3 >{{question.title}}</h3>
                    <button :id="question.id" v-on:click="showQuestion(question, $event)" >Вернуться</button>
                  </div>
                  <div >
                    <p >
                      {{question.description}}
                    </p>
                  </div>
                </div>
              </li>
              
              <script>
export default {
  name: "FAQContent",
  data() {
    return {
      questions: [
        {id: 1, title: 'Вопрос1', description: 'lorem lorem lorem', isShow: false, isHide: true},
        {id: 2, title: 'Вопрос2', description: 'lorem lorem lorem', isShow: false, isHide: true},
        {id: 3, title: 'Вопрос3', description: 'lorem lorem lorem', isShow: false, isHide: true},
      ]
    }
  },
  computed: {
    hideQuestions: function (){
    }
  },
  methods: {
    showQuestion: function (question,event) {
      question.isHide = !question.isHide;
      question.isShow = !question.isShow;
    }
  }
}
</script>

CodePudding user response:

you can add new data property called: activeQuestion.

  • When a question is clicked => assign it to activeQuestion

  • When cancel is clicked => assign null to activeQuestion

Then in template, make an if condition to check what to render:

  • render List If there is no activeQuestion

  • render the active Question if assigned

Working Demo:

  • Related