0

i'm beginner in Vue and i need to get button id which i set it like the code below:

<li v-for="subject in this.$root.$data.LoggedUserSubjects">
          <button :style="btnStyleObject" :id="subject.subject.id" @click="showSessions(this.id)" class="btn btn-primary">{{subject.subject.name}}</button>
</li>

as you can see i need to pass the id to showSessions function but i get this error when i click the button

Cannot read property 'id' of null

how can i get the id

thanks a lot

2
  • 1
    Without having more context - I'm guessing it's throwing an error on this.id ? change that to subject.subject.id. Commented Mar 17, 2020 at 10:54
  • yes that's right subject.subject.id did it ...thanks a lot Commented Mar 17, 2020 at 12:18

1 Answer 1

2

The this will have a scope of the entire component. If there is no id declared in the script section, it will throw an error.

Here, you can directly send the id to the function as follows,

<li v-for="subject in this.$root.$data.LoggedUserSubjects">
    <button :style="btnStyleObject" :id="subject.subject.id" @click="showSessions(subject.subject.id)" class="btn btn-primary">{{subject.subject.name}}</button>
</li>

Or you can call the function without any parameters and get the target item as follows

<li v-for="subject in this.$root.$data.LoggedUserSubjects">
    <button :style="btnStyleObject" :id="subject.subject.id" @click="showSessions" class="btn btn-primary">{{subject.subject.name}}</button>
</li>

Inside the method:

showSessions:function(e){
   console.log(e.target.id); // this will give you the id of the target element.
}
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.