一、前言
ref
有三种用法:
ref
作用在普通元素上,用this.ref.name
获取dom
元素;ref
作用子组件上,用this.ref.name
获取到组件实例,可以使用组件所有方法。- 利用
v-for
和ref
获取一组数据或dom
节点
二、注意事项
ref
需要在dom
渲染完成后应用,在使用时确保dom
已经渲染完成。比如在生命周期mounted(){}
钩子中调用,或者在this.$nextTick(()=>{})
中调用。- 如果
ref
是循环出来的,有多个重名,那么ref
值会是一个数组 ,此时要拿到单个ref
只需要循环就可以。
三、应用
3.1 ref 作用在外组件
<div id="ref-outside-component" v-on:click="consoleRef">
<component-father ref="outsideComponentRef">
</component-father>
<p>ref在外面的组件上</p>
</div>
var refoutsidecomponentTem={
template:"<div class='childComp'><h5>我是子组件</h5></div>"
};
var refoutsidecomponent=new Vue({
el:"#ref-outside-component",
components:{
"component-father":refoutsidecomponentTem
},
methods:{
consoleRef:function () {
console.log(this); // #ref-outside-component vue实例
console.log(this.$refs.outsideComponentRef); // div.childComp vue实例,组件实例
}
}
});
3.2 ref 作用在外元素
<div id="ref-outside-dom" v-on:click="consoleRef" >
<component-father>
</component-father>
<p ref="outsideDomRef">ref在外面的元素上</p>
</div>
var refoutsidedomTem={
template:"<div class='childComp'><h5>我是子组件</h5></div>"
};
var refoutsidedom=new Vue({
el:"#ref-outside-dom",
components:{
"component-father":refoutsidedomTem
},
methods:{
consoleRef:function () {
console.log(this); // #ref-outside-dom vue实例
console.log(this.$refs.outsideDomRef); // <p>标签dom元素 ref在外面的元素上</p>
}
}
});
3.3 ref 作用在里面元素上--局部注册组件
<div id="ref-inside-dom">
<component-father>
</component-father>
<p>ref在里面的元素上</p>
</div>
var refinsidedomTem={
template:"<div class='childComp' v-on:click='consoleRef'>" +
"<h5 ref='insideDomRef'>我是子组件</h5>" +
"</div>",
methods:{
consoleRef:function () {
console.log(this); // div.childComp vue实例
console.log(this.$refs.insideDomRef); // <h5 >我是子组件</h5>
}
}
};
var refinsidedom=new Vue({
el:"#ref-inside-dom",
components:{
"component-father":refinsidedomTem
}
});
3.4 ref 作用在里面的元素上--全局注册组件
<div id="ref-inside-dom-all">
<ref-inside-dom-quanjv></ref-inside-dom-quanjv>
</div>
Vue.component("ref-inside-dom-quanjv",{
template:"<div class='insideFather'> " +
"<input type='text' ref='insideDomRefAll' v-on:input='showinsideDomRef'>" +
" <p>ref在里面的元素上--全局注册 </p> " +
"</div>",
methods:{
showinsideDomRef:function () {
console.log(this); //这里的this其实还是div.insideFather
console.log(this.$refs.insideDomRefAll); // <input type="text">
}
}
});
var refinsidedomall=new Vue({
el:"#ref-inside-dom-all"
});