Mav
Mav

Reputation: 1190

How can I access elements in v-for

I have a v-for loop iterating over an array called projects. I have another array called selectedProjects. When a project element is clicked, I'd like to add a class called selected to that specific element, as well as add the project.id property of that index to selectedProjects. Maybe I'm going about the whole problem wrong, is there a "vue" way to achieve this?

<!-- The template -->
<div v-for="project in projects" class="project" @click="">
    <p><i class="fa fa-folder"></i>{{project.name}}</p>
</div>

The component's data:

data: function(){
    return {
        projects: [...],
        selectedProjects: [],
    }
},

Upvotes: 6

Views: 7627

Answers (3)

Shu  Yoshioka
Shu Yoshioka

Reputation: 466

I would add a key selected on project objects.

The template will be like this

<div v-for="project in projects" class="project" :class="{selected: project.selected}" @click="select(project)">
    <p><i class="fa fa-folder"></i>{{project.name}}</p>
</div>

And add select event. If you need selectedProjects array for some reason, you can have a computed function rather than having two arrays in data.

methods: {
    select(project) {
        project.selected = true
    }
},
computed: {
    selectedProjects () {
        return this.projects.filter(project => project.selected)
    }
}

Upvotes: 5

Husam Elbashir
Husam Elbashir

Reputation: 7197

You can make use of Vue's dynamic class bindings to achieve this. Let's say that each of your projects has a property called isSelected (false by default). Then you can do the following ..

<div v-for="project in projects" class="project" :class="{selected: project.isSelected}" @click="handleClick(project)">
    <p><i class="fa fa-folder"></i>{{project.name}}</p>
</div>

Then in your script ..

  methods: {
    handleClick(project) {
      project.isSelected = !project.isSelected
      if (project.isSelected) {
        this.selectedProjects.push(project.id)
      } else {
        this.selectedProjects.splice(this.selectedProjects.indexOf(project.id), 1)
      }

    }
  }

Upvotes: 2

Brian Lee
Brian Lee

Reputation: 18197

You got the right idea going, just add a click handler and a $ref:

@click="onProjectClicked(project.id)" ref="`project${project.id}`"

And the methods implementation:

methods: {
  onProjectClicked(id) {
     this.selectedProjects.push(id)
     this.$refs[`project${id}`].$el.addClass('selected')
  }
}

Upvotes: 2

Related Questions