Javascript Vue js 在输入字段中对 v-model 应用过滤器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36487310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:09:37  来源:igfitidea点击:

Vue js apply filter on v-model in an input field

javascriptjquerydatemomentjsvue.js

提问by Gustavo Bissolli

Hope someone can help me! I have made a directive wrapping the Jasny Bootstrap Plugin more specifically the input-mask thing and everything goes well!

希望可以有人帮帮我!我已经制定了一个指令来包装 Jasny Bootstrap 插件,更具体地说是输入掩码的东西,一切顺利!

Now I have made a custom filter supported by moment to format the date field!

现在我制作了一个由 moment 支持的自定义过滤器来格式化日期字段!

The date format that I receive from my backend application is YYY-MM-DD and I must show on the view as DD/MM/YYYY... I've tried v-model="date | myDate"but it didn't work properly!

我从后端应用程序收到的日期格式是 YYY-MM-DD,我必须在视图中显示为 DD/MM/YYYY...我试过了,v-model="date | myDate"但它没有正常工作!

JS

JS

Vue.directive('input-mask', {
  params: ['mask'],

  bind: function() {
    $(this.el).inputmask({
      mask: this.params.mask
    });

  },
});

Vue.filter('my-date', function(value, formatString) {

  if (value != undefined)
    return '';

  if (formatString != undefined)
    return moment(value).format(formatString);

  return moment(value).format('DD/MM/YYYY');

});

var vm = new Vue({
  el: 'body',
  data: {
    date: '2015-06-26',
  }
});

HTML

HTML

<label>Date</label>
<input type="text" class="form-control" v-input-mask mask="99/99/9999" v-model="date">
<p>{{ date | myDate 'dd/mm/yyyy' }}</p>

There is the JSBinif somebody's interested!

如果有人感兴趣,这里有JSBin

Thanks in advance!

提前致谢!

EDIT: Explaining better what I expect =)

编辑:更好地解释我的期望 =)

When the page first load the input receive the value of 2015-06-26 and I would like to show that value as DD/MM/YYYY so 26/06/2015! It works properly only after I start typing something!

当页面第一次加载时,输入会收到 2015-06-26 的值,我想将该值显示为 DD/MM/YYYY 所以 26/06/2015!只有在我开始输入内容后它才能正常工作!

采纳答案by crabbly

I understand what you are trying to do, however, because of the two way binding when using v-model, it may be better to just format the date as you receive it from the server, and then, use it with the desired format in your front-end app ('DD/MM/YYYY').

我理解您正在尝试做什么,但是,由于使用 v-model 时的双向绑定,最好在从服务器接收日期时格式化日期,然后将其与所需的格式一起使用您的前端应用程序 ( 'DD/MM/YYYY')。

When sending the data back to the back-end, you just format it back to the desired server format ('YYYY-MM-DD').

将数据发送回后端时,您只需将其格式化回所需的服务器格式 ( 'YYYY-MM-DD')。

In your Vue app, the work flow would be something like this:

在您的 Vue 应用程序中,工作流程如下所示:

 new Vue({
    el: 'body',
    data: {
      date: null,
    },
    methods: {
        getDataFromServer: function() {
                // Ajax call to get data from server

                // Let's pretend the received date data was saved in a variable (serverDate)
                // We will hardcode it for this ex.
                var serverDate = '2015-06-26';

                // Format it and save to vue data property
                this.date = this.frontEndDateFormat(serverDate);
        },
        saveDataToServer: function() {
            // Format data first before sending it back to server
            var serverDate = this.backEndDateFormat(this.date);

            // Ajax call sending formatted data (serverDate)
        },
        frontEndDateFormat: function(date) {
            return moment(date, 'YYYY-MM-DD').format('DD/MM/YYYY');
        },
        backEndDateFormat: function(date) {
            return moment(date, 'DD/MM/YYYY').format('YYYY-MM-DD');
        }
    }
  });

This works well for me, hope it helps.

这对我来说效果很好,希望它有所帮助。

Here is a fiddle for it:

这是一个小提琴:

https://jsfiddle.net/crabbly/xoLwkog9/

https://jsfiddle.net/crabbly/xoLwkog9/

Syntax UPDATE:

语法更新:

    ...
    methods: {
        getDataFromServer() {
                // Ajax call to get data from server

                // Let's pretend the received date data was saved in a variable (serverDate)
                // We will hardcode it for this ex.
                const serverDate = '2015-06-26'

                // Format it and save to vue data property
                this.date = this.frontEndDateFormat(serverDate)
        },
        saveDataToServer() {
            // Format data first before sending it back to server
            const serverDate = this.backEndDateFormat(this.date)

            // Ajax call sending formatted data (serverDate)
        },
        frontEndDateFormat(date) {
            return moment(date, 'YYYY-MM-DD').format('DD/MM/YYYY')
        },
        backEndDateFormat(date) {
            return moment(date, 'DD/MM/YYYY').format('YYYY-MM-DD')
        }
    }
  })

回答by james2doyle

I had a similar problem when I wanted to uppercase an input value.

当我想大写输入值时,我遇到了类似的问题。

This is what I ended up doing:

这就是我最终做的:

// create a directive to transform the model value
Vue.directive('uppercase', {
  twoWay: true, // this transformation applies back to the vm
  bind: function () {
    this.handler = function () {
      this.set(this.el.value.toUpperCase());
    }.bind(this);
    this.el.addEventListener('input', this.handler);
  },
  unbind: function () {
    this.el.removeEventListener('input', this.handler);
  }
});

Then I can use this directive on the input field with a v-model.

然后我可以在输入字段上使用这个指令v-model

<input type="text" v-model="someData" v-uppercase="someData">

Now, whenever I type into this field or change someData, the value is transformed to uppercase.

现在,每当我输入此字段或更改时someData,该值都会转换为大写。

This essentially did the same thing as I hoped v-model="someData | uppercase"would do. But of course, you can't do that.

这基本上和我希望v-model="someData | uppercase"做的一样。但当然,你不能那样做。

In summation: make a directive that transforms the data, not a filter.

总而言之:制作一个转换数据指令,而不是一个 filter

回答by krchun

This is how I implemented a vue filter for a v-model using the watch callback, this won't update the value on load.

这就是我使用 watch 回调为 v-model 实现 vue 过滤器的方式,这不会在加载时更新值。

Vue.filter('uppercase', function (value) {
    return value.toUpperCase();
});

The html:

html:

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

And the watch callback:

和手表回调:

watch:{
   someData(val) {
       this.someData = this.$options.filters.uppercase(val);
    },
}

回答by Samidjo

Go to main.js and add the following code :

转到 main.js 并添加以下代码:

import moment from 'moment'
Vue.filter('myDate', function (value) {
    if (value) {
        return moment(String(value)).format('dd/mm/yyyy')
    }
});

In your HTML do the following :

在您的 HTML 中执行以下操作:

<label>Date</label>
<v-text-field :value="date | myDate" @input="value=>date=value"></v-text-field>
<p>{{ date | myDate 'dd/mm/yyyy' }}</p>

So we used above v-bind to bind the value and @input event handler to have the v-model functionality.

所以我们使用上面的 v-bind 来绑定值和 @input 事件处理程序以具有 v-model 功能。

回答by Jeff

When you get the value initially, adjust it to fit the input. I got it working in the readyfunction, but you could do this after your DB call as well:

当您最初获得该值时,对其进行调整以适合输入。我让它在ready函数中工作,但你也可以在你的数据库调用之后这样做:

ready: function(){    
  var year = this.date.substr(0, 4);
  var monDay = this.date.substr(5,5);
  var result = monDay + "-" + year;
  this.date = result.replace(/-/g,"/");
}

You may have to do something similar on the way back up to your database as well.

您可能还需要在备份到数据库的过程中执行类似的操作。

回答by Jason Stewart

I've found that I can filter input using the ordinary component v-bind:value/ v-on:inputdance without resorting to dataor watchclauses if I just call $forceUpdate()after emitting the filtered value:

我发现我可以使用普通组件v-bind:value/ v-on:inputdance过滤输入,而无需求助于dataorwatch子句,如果我只是$forceUpdate()在发出过滤后的值后调用:

The Vue component:

Vue 组件:

{
  props: ['value'],
  methods: {
    mEmit: function(EVT) {
      const VAL      = EVT.target.value;
      var   FILTERED = myFilterFunction(VAL);
      this.$emit('input', FILTERED);
      this.$forceUpdate();
    }
  }
}

The component HTML (data is filtered as it is entered):

组件 HTML(数据在输入时被过滤):

  <input type="text" v-bind:value="value" v-on:input="mEmit($event)" />

Using the component:

使用组件:

<my-component v-model="myDataVar"></my-component>