示例:
<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.
方案:
问题:如何在不触发更新的情况下从输入中排除前缀?
答案 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...
}
}
}
你应该能够做到这一点,但检查我的评论。这可能是一个更好的解决方案。