How can I pass selected value to a vuejs function?
v-model
won't help I guess.
I need to set values for the filter after
item: items | orderBy sortKey reverse
where reverse
and sortKey
are dynamic values.
html
<select class="sort-filter" v-on="change: sortBy(???)">
<option value="title asc">Title (A-Z)</option>
<option value="title desc">Title (Z-A)</option>
<option value="price asc">Price (Min. - Max.)</option>
<option value="price desc">Price (Max. - Min.)</option>
</select>
js
methods: {
sortBy: function (sortKey) {
console.log(sortKey)
}
}
You have several ways to do it.
Edit: Improved 2)
It is possible to use v-model just like in 2) but instead of using the value directly in your orderBy filter, you can use computed properties
computed: {
sortKey: {
get: function() {
return this.sorting.split(' ')[0]; // return the key part
}
},
sortOrder: {
get: function() {
return this.sorting.split(' ')[1]; // return the order part
}
}
}
This way, sortKey and sortOrder will be available like a normal property in you filter:
v-repeat="items | orderBy sortKey sortOrder"
1) Use javascript event:
If you don't specify any parameter, the native event object will be passed automatically
<select class="sort-filter" v-on:change="sortBy">
You can then use it like this:
methods: {
sortBy: function(e) {
console.log(e.target.value);
},
}
2) Using v-model
You can add the v-model directive
<select name="test" v-model="sorting" v-on:change="sortBy">
This way the sorting
value will be updated on every change.
You can add this value in the data object of you ViewModel to be more clear:
data: {
sorting: null // Will be updated when the select value change
}
You can then access the value like in your method:
methods: {
sortBy: function() {
console.log(this.sorting);
},
}
If you just need to update the sortKey
value, this method is not even necessary.
3) Other weird way
You can apparently use your model value as a parameter.
<select name="test" v-model="sortKey" v-on:change="sortBy(sortKey)">
This is working but I don't really see the point.
methods: {
sortBy: function(sortKey) {
console.log(sortKey);
},
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With