1

kinda new to vue, I have mapped out some data from my initial data object in vue.js I am trying to hide and show only the items within that iteration of the mapping when the user selects the heading. I am using the isHidden prop in vue to hide and show my list items but when selecting any heading it shows all the

  • tags instead of those associated with that specific header.

    anyone know the proper way to do this? should I use some index or id from e.target? or should I give each list item a 'hidden' property and change it that way somehow?

    here's my list that I mapped out

    <div v-for="item in list">
       <h4 v-on:click="viewItemsinCat()">{{item.category}}</h4>
       <ul>
          <li v-if="!isHidden" v-for="item in item.food">
             {{item}}
          </li>
       </ul>
    </div>
    

    then I have my data like so:

    data: {
      list: [{
        category: 'Baked goods',
        food: ['bread', 'cookie', 'butter', 'powder']
      }, {
        category: 'meats',
        food: ['chicken', 'turkey', 'beef']
      }, {
        category: 'fruits',
        food: ['bannana', 'apple', 'pineapple']
      }, {
        category: 'canned goods',
        food: ['tomatoes', 'green beans', 'corn']
      }, {
        category: 'veggies',
        food: ['broccoli', 'celery', 'lettuce']
      }, {
        category: 'pantry',
        food: ['broom', 'mop', 'dried beans']
      }, ],
      isHidden: true,
    }
    

    then I have my method to alter isHidden

    viewItemsinCat: function(){
       this.isHidden = false
    },
    
  • 1
    • I would use a map function on your list to add a isHidden property to each element of your list. That would be the easiest. ex) this.list = this.list.map( elem => elem.isHidden = //some logic here); Commented Apr 8, 2020 at 20:10

    1 Answer 1

    1

    Add a selected property to contain the currently selected item when the user clicks:

    data() {
      return {
        selected: null,
        list: [...]
      }
    }
    
    <div v-for="item in list">
      <h4 v-on:click="selected=item.category">{{item.category}}</h4>
      <ul v-if="selected==item.category">
        <li v-for="food in item.food">
          {{ food }}
        </li>
      </ul>
    </div>
    

    Here's a demo

    Sign up to request clarification or add additional context in comments.

    Comments

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.