Reputation: 26768
The title was kinda long-winded but the question itself is pretty simple.
So I'm looping over some strings and want to make a button for each. On click, the button will call a Vue method. I want to bind the string into the HTML element somehow - it will be more clear with the code:
<li v-for="(name, idx) in $store.state.lobby" :key="idx">
<button data-name="{{name}}" v-on:click='send_game_request'> request game </button>
</li>
so, as you can see, this is very simple. When the send_game_request
method gets run, it can read the name
off the data-name
attribute and do what it needs to with that information.
But, this is invalid syntax, because {{name}}
raises an error. I'm really hoping I don't have to wrap each button into it's own sub-component, because that is just extra boilerplate that's not necessary.
I've seen other examples that use v-bind
but I don't really have any need to store this information in the component's internal state. I literally just need to know what button was pressed.
Upvotes: 2
Views: 935
Reputation: 138286
You can pass the name
as an argument with an inline handler:
<button @click="send_game_request($event, name)">
where $event
is the original event data.
Upvotes: 3
Reputation: 1548
In addition to what Tony mentions in his answer,
<li v-for="(name, idx) in $store.state.lobby" :key="idx">
<button :data-name="name" v-on:click='send_game_request'> request game </button>
</li>
You could then extract value of name with datasets like so:
function send_game_request(event){
const name = event.target.dataset.name;
}
NOTE: In this instance you don't need to explicitly pass the $event
into your v-on:click
function binding, it will already be made available by Vue. So, you can simply invoke your method with the event argument.
Upvotes: 3