vue.js 1.x与2.0中js实时监听input值的变化

一、vuejs 2.0中js实时监听input

在2.0的版本中,vuejs把v-el 和 v-ref 合并为一个 ref 属性了,可以在组件实例中通过 $refs 来调用。这意味着 v-el:my-element 将写成这样: ref="myElement" , v-ref:my-component 变成了这样: ref="myComponent" 。绑定在一般元素上时,ref 指DOM元素,绑定在组件上时,ref 为一组件实例。

因为 v-ref 不再是一个指令了而是一个特殊的属性,它也可以被动态定义了。这样在和v-for 结合的时候是很有用的:

<p v-for="item in items" v-bind:ref="'item' + item.id"></p>

以前 v-el/v-ref 和 v-for 一起使用将产生一个DOM数组或者组件数组,因为没法给每个元素一个特定名字。现在你还仍然可以这样做,给每个元素一个同样的ref:

<p v-for="item in items" ref="items"></p>

和 1.x 中不同, $refs 不是响应的,因为它们在渲染过程中注册/更新。只有监听变化并重复渲染才能使它们响应。另一方面,设计$refs主要是提供给 js 程序访问的,并不建议在模板中过度依赖使用它。因为这意味着在实例之外去访问实例状态,违背了 Vue 数据驱动的思想。

下面给一个vuejs2.0版本的例子:

<div> <input type="text" v-model="items.type1" ref="type1"/> <input type="text" v-model="items.type2" ref="type2"/> <div>输入框一的内容:{{items.type1}}</div> <div>输入框二的内容:{{items.type2}}</div> </div> <script> var example1 = new Vue({ el: '#example', data: { items: { type1:'第一个输入框', type2:'第二个输入框' } }, ready:function(){ }, watch:{ items:{ handler:function(val,oldval){ console.log(this.$refs.type1.value); console.log(this.$refs.type2.value); }, deep:true } }, methods:{ } }) </script>

结果如图所示:

vue.js 1.x与2.0中js实时监听input值的变化

当在输入框输入文字的时候,js可以实时监听其指定输入框文本的值。

二、vuejs 1.x中js实时监听input

那么在vuejs 1.x的版本中是如何在js中监听某个指定的input的value变化的呢?

通过如下方式:

<input type="text" v-model="items.type1" v-el:texttype1/>

然后在vuejs中的watch中监听:

watch:{ items:{ handler:function(val,oldval){ console.log(this.$els.texttype1.value); }, deep:true } }

整体代码:

<div> <input type="text" v-model="items.type1" v-el:texttype1/> <input type="text" v-model="items.type2" v-el:texttype2/> <div>输入框一的内容:{{items.type1}}</div> <div>输入框二的内容:{{items.type2}}</div> </div> <script> var example1 = new Vue({ el: '#example', data: { items: { type1:'第一个输入框', type2:'第二个输入框' } }, ready:function(){ }, watch:{ items:{ handler:function(val,oldval){ console.log(this.$els.texttype1.value); }, deep:true } }, methods:{ } }) </script>

实现的效果如图所示:

vue.js 1.x与2.0中js实时监听input值的变化

当在输入框中输入文字时,js中实时监听其变化的值。

总结

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwwgsf.html