如何将选定的值传递给 vuejs 函数?
v-model
我猜不会有帮助。
之后我需要为过滤器设置值
项目:项目 | orderBy sortKey 反转
其中 reverse
和 sortKey
是动态值。
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)
}
}
最佳答案
您有多种方法可以做到这一点。
编辑:改进 2)
可以像 2) 一样使用 v-model,但是您可以使用 computed properties 而不是直接在 orderBy 过滤器中使用值
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 将像过滤器中的普通属性一样可用:
v-repeat="items | orderBy sortKey sortOrder"
1)使用javascript事件:
如果不指定任何参数,将自动传递原生事件对象
<select class="sort-filter" v-on:change="sortBy">
然后你可以像这样使用它:
methods: {
sortBy: function(e) {
console.log(e.target.value);
},
}
2) 使用 v-model
您可以添加 v-model 指令
<select name="test" v-model="sorting" v-on:change="sortBy">
这样 sorting
值将在每次更改时更新。
您可以在 ViewModel 的数据对象中添加此值以更加清晰:
data: {
sorting: null // Will be updated when the select value change
}
然后您可以像在您的方法中一样访问该值:
methods: {
sortBy: function() {
console.log(this.sorting);
},
}
如果你只是需要更新sortKey
的值,这个方法就没有必要了。
3)其他奇怪的方式
您显然可以将模型值用作参数。
<select name="test" v-model="sortKey" v-on:change="sortBy(sortKey)">
这是可行的,但我真的不明白这一点。
methods: {
sortBy: function(sortKey) {
console.log(sortKey);
},
}
关于vue.js - 将选定的值传递给 vuejs 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31272276/