vuejs2.0与1.x版本中怎样使用js实时访问input的值的变化

前端之家收集整理的这篇文章主要介绍了vuejs2.0与1.x版本中怎样使用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:

 ref="items">

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

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

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

结果如图所示:

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

vuejs 1.x中js实时监听input

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

 v-el:texttype1/>

然后在vuejs中的watch中监听:

watch:{
    items:{
        handler:functionthis.$els.texttype1.value);
        },deep:true
    }
}

整体代码

<div id="example">
    <input type="text" v-model="items.type1" v-el:texttype1/>
    <input type="text" v-model="items.type2" v-el:texttype2/>
    <div class="show">输入框一的内容:{{items.type1}}</div>
    <div class="show">输入框二的内容:{{items.type2}}</div>
</div>
<script>
    var example1 = new Vue({
      el: '#example''第二个输入框'.$els.texttype1.value);
                },methods:{
        
      }
    })
</script>

实现的效果如图所示:

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

猜你在找的Vue相关文章