Martyn Ball
Martyn Ball

Reputation: 4885

Vue inline click event `this` is undefined

i'm getting an error in the below code saying this is undefined.

<div class="location-list__item" v-for="(value, key) in locations.data">
    <div class="location-list__item--text"
         :class="{ selected: selected === key }"
         @click="() => { this.selected = key; this.manageSurrounding = false }">
        <i class="fas fa-compass"></i> {{ value.name }}
        <span v-if="value.changed" class="has-text-danger"> Changed</span>
    </div>
</div>

However if I change this line:

@click="() => { this.selected = key; this.manageSurrounding = false }"

to this

@click="selected = key"

It works fine, however I need to change manageSurrounding at the same time and I don't want to create a method for such a simple thing.

Upvotes: 0

Views: 877

Answers (3)

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 1767

You can do multiple assignments by using semicolon like the above statement which you have written.

<div class="location-list__item" v-for="(value, key) in locations.data">
    <div class="location-list__item--text"
         :class="{ selected: selected === key }"
         @click="selected = key;manageSurrounding = false">        # Like this
        <i class="fas fa-compass"></i> {{ value.name }}
        <span v-if="value.changed" class="has-text-danger"> Changed</span>
    </div>
</div>

Upvotes: 5

J&#225;nos Veres
J&#225;nos Veres

Reputation: 199

Just create a method and put in the update lines, you are better off on the long run, if your list is changing/reordering/re-rendering often.

It’s an optimization opportunity, so don’t try to force it in just because it seems small. Have a look at this answer: anonymus function in template

Upvotes: 0

Neha Jain
Neha Jain

Reputation: 126

You can use a anonymous function like,

<div onclick="return function()

 { selected = key; manageSurrounding = false }'

</div>

Upvotes: 1

Related Questions