Mr. Wilhelm
Mr. Wilhelm

Reputation: 31

Use v-if (with computed prop) inside v-for

Thanks for the help with displaying the edit-button only when i'm logged in.

The question I need help with is: Can I bind the whole {{ project.* }} which im looping through? to the "EditProject" component?

<EditProject :project="`${project}`">

Some info about my application: I am using Vuex to store all my data. Ideally I would like to just pass the hole project to the dialog, but I could also just pass the ID and then load just that one project from Vuex. EditProject is a new dialog windows in which I would like to be able to edit the project.

I am creating a list of projects. The projects are stored with Vuex and Firebase, and are loaded as a computed prop.

computed: {
  projects () {
    return this.$store.getters.loadedProjects
  }
}

Then i'm looping through all the projects and display title, date, description and creatorId.

<v-list>
 <div v-for="project in projects" :key="project.id">
   <p>{{ project.title }}</>
   <edit-project v-if="isSignedIn === project.creatorId">
 </div>

Here comes the tricky part. I want to display if project.creatorId is the same as the user logged in. "isSignedIn" is a computed prop:

isSignedIn () {
  if (this.$store.getters.user !== null &&  this.$store.getters.user !== undefined) {
    return true
  } else return false
},

Summary: The v-for loop contains a {{ project.creatorId }} which I want chech if is the same as this.$store.getters.user, And then display the "Edit-project" if match. Edit-project is a button that opens a dialog. This is a simplified version of my application.

I have tried v-if="checkUserIdMethod(${project.id})", and all kind of variations, but had to resort to this website. I'm pretty sure I could get it to work with them backticks ``

Upvotes: 0

Views: 69

Answers (2)

sundeqvist
sundeqvist

Reputation: 171

You really should be looking to compare the current users id, instead of building extra methods to find out if the current user matches based on isSignedIn, which means you could write:

v-if="$store.getters.user.id === project.creatorId",

or alternatively refactor it into a separate method:

v-if="isCurrentUser(project.creatorId)"

isCurrentUser(creatorId) {
  return this.$store.getters.user.id === creatorId;
}

also, if you still need isSignedIn, I would simplify it to increase readability:

isSignedIn () {
  return this.$store.getters.user !== null && this.$store.getters.user !== undefined;
},

Upvotes: 0

Farouk M
Farouk M

Reputation: 1295

Have you tried to filter the list before rendering it like :

computed: {
  userProjects () {
    return this.$store.getters.loadedProjects.filter(p => p.creatorId === this.$store.getters.user.id   )
  }
}

If you use it in many components you can also make the filter in the store and call it like :

computed: {
  userProjects () {
    return this.$store.getters.userLoadedProjects(userId)
  }
}

Upvotes: 1

Related Questions