这篇文章主要讲解了“vue中ref如何用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“vue中ref如何用”吧!
vue中ref的用法有三种,分别是:1.ref加在普通的元素上,用this.ref.name获取dom元素;2.ref加在子组件上,用this.ref.name 获取组件实例,可以使用组件的所有方法;3.利用v-for和ref获取一组数组或者dom节点。
示例:
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实例,组件实例
}
}
});
2.ref作用在外面元素上。
//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.ref使用在里面的元素上,局部注册组件。
//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
}
});
4.ref使用在里面的元素上,全局注册组件。
//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"
});
感谢各位的阅读,以上就是“vue中ref如何用”的内容了,经过本文的学习后,相信大家对vue中ref如何用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://www.zhuangjiba.com/help/32108.html