Vue.js中ref ($refs)用法举例总结

原文地址:http://www.cnblogs.com/xueweijie/p/6907676.html

 

<div id="app"> <input type="text" ref="input1"/> <button @click="add">添加</button></div>


<script>new Vue({ el: "#app", methods:{ add:function(){ this.$refs.input1.value ="22"; //this.$refs.input1 减少获取dom节点的消耗 } }})</script>


一般来讲,获取DOM元素,需document.querySelector(".input1")获取这个dom节点,然后在获取input1的值。

但是用ref绑定之后,我们就不需要在获取dom节点了,直接在上面的input上绑定input1,然后$refs里面调用就行。

然后在javascript里面这样调用:this.$refs.input1  这样就可以减少获取dom节点的消耗了

 

以下内容:

作者:该帐号已被查封
链接:http://www.jianshu.com/p/3bd8a2b07d57
來源:简书

看Vue.js文档中的ref部分,自己总结了下ref的使用方法以便后面查阅。

一、ref使用在外面的组件上

HTML 部分

1 <div id="ref-outside-component" v-on:click="consoleRef">2 <component-father ref="outsideComponentRef">3 </component-father>4 <p>ref在外面的组件上</p>5 </div>

 

js部分

 1 var refoutsidecomponentTem={ 2 template:"<div class=‘childComp‘><h5>我是子组件</h5></div>" 3 }; 4 var refoutsidecomponent=new Vue({ 5 el:"#ref-outside-component", 6 components:{ 7 "component-father":refoutsidecomponentTem 8 }, 9 methods:{10 consoleRef:function () {11 console.log(this); // #ref-outside-component vue实例12 console.log(this.$refs.outsideComponentRef); // div.childComp vue实例13 }14 }15 });

 

二、ref使用在外面的元素上

HTML部分

1 <!--ref在外面的元素上-->2 <div id="ref-outside-dom" v-on:click="consoleRef" >3 <component-father>4 </component-father>5 <p ref="outsideDomRef">ref在外面的元素上</p>6 </div>

 

JS部分

 1 var refoutsidedomTem={ 2 template:"<div class=‘childComp‘><h5>我是子组件</h5></div>" 3 }; 4 var refoutsidedom=new Vue({ 5 el:"#ref-outside-dom", 6 components:{ 7 "component-father":refoutsidedomTem 8 }, 9 methods:{10 consoleRef:function () {11 console.log(this); // #ref-outside-dom vue实例12 console.log(this.$refs.outsideDomRef); // <p> ref在外面的元素上</p>13 }14 }15 });

三、ref使用在里面的元素上---局部注册组件

HTML部分

1 <!--ref在里面的元素上-->2 <div id="ref-inside-dom">3 <component-father>4 </component-father>5 <p>ref在里面的元素上</p>6 </div>

JS部分

 1 var refinsidedomTem={ 2 template:"<div class=‘childComp‘ v-on:click=‘consoleRef‘>" + 3 "<h5 ref=‘insideDomRef‘>我是子组件</h5>" + 4 "</div>", 5 methods:{ 6 consoleRef:function () { 7 console.log(this); // div.childComp vue实例 8 console.log(this.$refs.insideDomRef); // <h5 >我是子组件</h5> 9 }10 }11 };12 var refinsidedom=new Vue({13 el:"#ref-inside-dom",14 components:{15 "component-father":refinsidedomTem16 }17 });

 

四、ref使用在里面的元素上---全局注册组件

HTML部分

1 <!--ref在里面的元素上--全局注册-->2 <div id="ref-inside-dom-all">3 <ref-inside-dom-quanjv></ref-inside-dom-quanjv>4 </div>
 

JS部分

 

 1 Vue.component("ref-inside-dom-quanjv",{ 2 template:"<div class=‘insideFather‘> " + 3 "<input type=‘text‘ ref=‘insideDomRefAll‘ v-on:input=‘showinsideDomRef‘>" + 4 " <p>ref在里面的元素上--全局注册 </p> " + 5 "</div>", 6 methods:{ 7 showinsideDomRef:function () { 8 console.log(this); //这里的this其实还是div.insideFather 9 console.log(this.$refs.insideDomRefAll); // <input type="text">10 }11 }12 });13
14 var refinsidedomall=new Vue({15 el:"#ref-inside-dom-all"16 });

相关文章