[英]How create a v-model modifier to a VueJS Component?
In VueJS there is some v-model
modifies that pre-parse the binded value, for instance v-model.trim
that removes whitespaces from the string.在 VueJS 中,有一些
v-model
修改可以预先解析绑定的值,例如v-model.trim
从字符串中删除空格。
How can I create my own modifier?如何创建自己的修饰符? for instance
v-model.myparse
Today um using something like:例如
v-model.myparse
今天嗯使用类似的东西:
computed: {
name: {
get: function () { return parse(this._name);},
set: function (value) { _name = parse(value);}
}
What is very verbose.什么很冗长。
I would it to be reusable to do something like:我希望它可以重复使用以执行以下操作:
<input v-model.myparse="name" name='n1'/>
<input v-model.myparse="name" name='n2'/>
<input v-model.myparse="name" name='n3'/>
<input v-model.myparse="name" name='n4'/>
computed properties with setters seems to do part of the work, but it is really useful with some few variables only, it becomes very verbose with a lot of properties.带有 setter 的计算属性似乎完成了部分工作,但它只对一些变量非常有用,它变得非常冗长,有很多属性。
First, adding adding a custom modified to v-model
is under discussion but not yet implemented.首先,添加自定义修改到
v-model
正在讨论中,但尚未实现。
If it was implemented, you could extend the v-model
and add a modifier to it.如果已实现,您可以扩展
v-model
并为其添加修饰符。
Since that is not possible, you have a couple of options left, one of which is to use :value
instead of v-model.由于这是不可能的,因此您还有几个选择,其中之一是使用
:value
而不是 v-model。 Because v-model
is just a syntactic sugar of following:因为
v-model
只是以下的语法糖:
<input type="text" :value="message" @input="message = $event.target.value">
The above code is the same as:上面的代码与以下代码相同:
<input type="text" v-model="message">
So, I suggest you replace the logic for the @input
to something like this:因此,我建议您将
@input
的逻辑替换为以下内容:
<input type="text" :value="message" @input="getModel"> <input type="text" :value="message" @input="getModel">
Now, you can use a function to return a modified value as:现在,您可以使用函数将修改后的值返回为:
methods: {
getModel ($event) {
return $event.target.value.trim()
}
}
But all of what I mentioned can still be done with the v-model
if you use a function.但是,如果您使用函数,我提到的所有内容仍然可以使用
v-model
完成。
Of course it goes without saying, you can create your own custom directive also.当然不用说,您也可以创建自己的自定义指令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.