本文介绍了如何为 VueJS 组件创建 v-model 修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 VueJS 中,有一些 v-model 修改预解析绑定值,例如 v-model.trim 从字符串中删除空格.

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.

如何创建自己的修饰符?例如 v-model.myparse今天嗯使用类似的东西:

How can I create my own modifier? for instance v-model.myparseToday um using something like:

computed: {
  name: {
    get: function () { return parse(this._name);},
    set: function (value) { _name = parse(value);}
  }

什么是非常冗长的.

我希望它可以重复使用以执行以下操作:

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'/>

使用 setter 计算的属性似乎可以完成部分工作,但它只对少数几个变量很有用,如果有很多属性,它会变得非常冗长.

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.

推荐答案

首先在 但尚未实施.

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.

因为这是不可能的,所以您还有几个选择,其中之一是使用 :value 而不是 v-model.因为 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. Because v-model is just a syntactic sugar of following:

  <input type="text" :value="message" @input="message = $event.target.value">

以上代码同:

  <input type="text" v-model="message">

所以,我建议你将 @input 的逻辑替换成这样:

So, I suggest you replace the logic for the @input to something like this:

现在,您可以使用函数返回修改后的值:

Now, you can use a function to return a modified value as:

methods: {
  getModel ($event) {
    return $event.target.value.trim()
  }
}

但是如果你使用函数,我提到的所有内容仍然可以通过 v-model 完成.

But all of what I mentioned can still be done with the v-model if you use a function.

当然不用说,您可以创建自己的自定义指令 还有.

Of course it goes without saying, you can create your own custom directive also.

这篇关于如何为 VueJS 组件创建 v-model 修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 06:32