Repeated elements have the same expand variable

2020-05-07 06:20发布

Hello i have some code from vuetify (https://vuetifyjs.com/en/components/cards#custom-actions)

so i edited code like this:

<template>

<div>
  <div v-for="item in 3" :key="item">

  <v-layout row >
    <v-flex xs12 sm6 offset-sm3>
      <v-card>
        <v-img
          src="https://cdn.vuetifyjs.com/images/cards/sunshine.jpg"
          height="200px"
        >
        </v-img>

        <v-card-title primary-title>
          <div>
            <div class="headline">Top western road trips</div>
            <span class="grey--text">1,000 miles of wonder</span>
          </div>
        </v-card-title>

        <v-card-actions>
          <v-btn flat>Share</v-btn>
          <v-btn flat color="purple">Explore</v-btn>
          <v-spacer></v-spacer>
          <v-btn icon @click="show = !show">
            <v-icon>{{ show ? 'keyboard_arrow_down' : 'keyboard_arrow_up' }}</v-icon>
          </v-btn>
        </v-card-actions>

        <v-slide-y-transition>
          <v-card-text v-show="show">
            I'm a thing. But, like most politicians, he promised more than he could deliver. You won't have time for sleeping, soldier, not with all the bed making you'll be doing. Then we'll go with that data file! Hey, you add a one and two zeros to that or we walk! You're going to do his laundry? I've got to find a way to escape.
          </v-card-text>
        </v-slide-y-transition>
      </v-card>
    </v-flex>
  </v-layout>

  </div>
 </div>
</template>

<script>
export default {
   data: () => ({
    show: false
  })
}
</script>

The problem is the show variable. onClick every element expands.

How can i set vor every element a own variable? or that on click only this element will expand?

2条回答
SAY GOODBYE
2楼-- · 2020-05-07 06:24

You've got several options.

The example is a bit artificial as it uses <div v-for="item in 3" :key="item">. In a real use case you'd likely be iterating over an array of objects and you could hold a show value within each object.

If storing it in the objects isn't an option then you could (somewhat painfully) maintain a separate array for the show values, using the index to tie the two arrays together.

But probably the best solution is to extract a new component. Generally when you have a v-for with some sort of editable state it is worth considering extracting a new component as it usually ends up being the simplest solution. In this case those components could each hold their own show value.

So:

<div v-for="item in 3" :key="item">

would become:

<my-new-component v-for="item in 3" :key="item">

and you'd move all the rest of the template into my-new-component.

查看更多
Viruses.
3楼-- · 2020-05-07 06:26

OK thank you i will Test this

I found an example to do this

https://vuejs.org/v2/guide/components.html

查看更多
登录 后发表回答