将选定的值传递给 vuejs 函数 [英] Pass selected value to vuejs function
问题描述
如何将选定的值传递给 vuejs 函数?v-model
我猜没用.
How can I pass selected value to a vuejs function?
v-model
won't help I guess.
我需要在之后设置过滤器的值item: 物品 |orderBy sortKey 反向
其中 reverse
和 sortKey
是动态值.
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.
改进 2)
可以像在 2) 中一样使用 v-model,但不是直接在 orderBy 过滤器中使用该值,您可以使用 计算属性
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
}
}
}
这样,sortKey 和 sortOrder 将像过滤器中的普通属性一样可用:
This way, sortKey and sortOrder will be available like a normal property in you filter:
v-repeat="items | orderBy sortKey sortOrder"
1) 使用 javascript 事件:
如果不指定任何参数,将自动传递原生事件对象
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) 使用 v-model
您可以添加 v-model 指令
You can add the v-model directive
<select name="test" v-model="sorting" v-on:change="sortBy">
这样 sorting
值将在每次更改时更新.
This way the sorting
value will be updated on every change.
你可以在你的ViewModel的数据对象中添加这个值更清晰:
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);
},
}
如果你只需要更新sortKey
的值,这个方法就没有必要了.
If you just need to update the sortKey
value, this method is not even necessary.
3) 其他奇怪的方式
您显然可以使用您的模型值作为参数.
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);
},
}
这篇关于将选定的值传递给 vuejs 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!