如何在输入[type = text]中分隔vue.js输入值和显示值?

时间:2017-06-01 07:03:14

标签: vue.js

示例:

<span class='prefix'>+{{ prefix }}</span>
<input type='tel' v-model='phone'>

应该展示什么

When phone === '790012345678', it is actually
prefix = '7'
phone = '90012345678'

并相应地显示

<span class='prefix'>+7</span>
<input type='tel' value='90012345678'>

当用户从输入中删除值时,也会删除前缀。

问题(jsfiddle http://jsfiddle.net/4qqza69k/48/

I use watcher for `phone`.
When user changes something inside `input` watcher must update value for `phone`, but this way it is triggered again and it receives updated (incorrect) value.

方案:

  1. 手机等于7-100-200-30-40 prefix = +7,phone = 1002003040
  2. 手机等于7 prefix = + 7,phone =''
  3. 手机等于7123 prefix = + 7,phone = 123
  4. 电话是空的 prefix ='',phone =''
  5. 问题:如何在不触发更新的情况下从输入中排除前缀?

2 个答案:

答案 0 :(得分:0)

我认为您需要将v-model重写为更明确的v-on + v-bind对并听取input的电话号码,同时分别计算前缀和其余部分:

new Vue({
  el: '#app',
  data: {
    prefix: '',
    phone: '', // full phone number
  },
  methods: {
    handleInput: function(e) {
      if (e.target.value === '') this.prefix = '';
      if (this.prefix !== '') {
      	this.phone = this.prefix + e.target.value;
      } else {
      	const v = e.target.value;
        this.phone = v;
        this.prefix = v.slice(0,1);
      }
    }
  },
  computed: {
    withoutPrefix: function() {
      return (this.prefix !== '') ? this.phone.slice(1) : ''
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <span class='prefix'>+{{ prefix }}</span>
  <input type='tel' @input="handleInput" :value="withoutPrefix">
  <p>Phone: {{ phone }}</p>
</div>

答案 1 :(得分:0)

它并不完全有效,因为我对你的例子感到有点困惑,但我认为一种方法是使用计算的getter / setter。

data() {
    return {
        hiddenInputValue: ''
    }
},
computed: {
    inputValue: {
        get() {
            return this.hiddenInputValue;
        },
        set(val) {
            // do something with the input value...
            this.hiddenInputValue = // assign a modified version of the input value...
        }
    }
}

你应该能够做到这一点,但检查我的评论。这可能是一个更好的解决方案。