这篇文章主要为大家介绍了Vue中$refs和$nextTick的使用方法,文中的示例代码讲解详细,对我们学习Vue有一定帮助,需要的可以参考一下
1、$refs简介
$refs是vue提供的获取真实dom的方法。
$refs获取DOM元素
[使用步骤]:
将ref属性添加到原生DOM元素中,以使用此属性获取原生DOM元素。$参考文献
[代码演示]:
lt;templategt; lt;divgt; lt;h1gt;获取原生的DOM元素lt;/h1gt; lt;h4 id="h" ref="myH"gt;我是h4标签lt;/h4gt; lt;/divgt;lt;/templategt;lt;scriptgt;export default { // 在挂载之后获取原生dom mounted() { console.log(document.getElementById("h")); // this.$refs是vue对象中特有的属性 console.log(this.$refs.myH); },};lt;/scriptgt;lt;stylegt;lt;/stylegt;
[控制台效果]:
$refs获取组件对象
[代码演示]:
lt;templategt; lt;divgt; lt;h1gt;获取组件对象lt;/h1gt; lt;Demo ref="myCom"gt;lt;/Demogt; lt;/divgt;lt;/templategt;lt;scriptgt;import Demo from "@/components/Demo";export default { mounted() { console.log(this.$refs.myCom); // 获取子组件对象 let demo = this.$refs.myCom; // 调用子组件中的方法 demo.fn(); }, components: { Demo, },};lt;/scriptgt;lt;stylegt;lt;/stylegt;
[效果展示]:
2、$nextTick基本使用
$nextTick等待dom更新,然后执行方法中的函数体。
vue异步更新DOM
[vue异步更新演示]:
lt;templategt; lt;divgt; lt;h1gt;获取组件对象lt;/h1gt; lt;Demo ref="myCom"gt;lt;/Demogt; lt;/divgt;lt;/templategt;lt;scriptgt;import Demo from "@/components/Demo";export default { mounted() { console.log(this.$refs.myCom); // 获取子组件对象 let demo = this.$refs.myCom; // 调用子组件中的方法 demo.fn(); }, components: { Demo, },};lt;/scriptgt;lt;stylegt;lt;/stylegt;
[效果演示]:
利用$nextTick解决以上问题
[代码演示]:
lt;templategt; lt;divgt; lt;pgt;vue异步更新domlt;/pgt; lt;p ref="mycount"gt;{{ count }}lt;/pgt; lt;button @click="add1"gt;点击+1,马上获取数据lt;/buttongt; lt;/divgt;lt;/templategt;lt;scriptgt;export default { data() { return { count: 0, }; }, methods: { add1() { this.count++; // console.log(this.$refs.mycount.innerHTML); // 解决异步更新问题 // dom更新完成之后会顺序执行this.$nextTick()中的函数体 this.$nextTick(() =gt; { console.log(this.$refs.mycount.innerHTML); }); }, },};lt;/scriptgt;lt;stylegt;lt;/stylegt;
[效果演示]:
$nextTick使用场景
[代码演示]:
lt;templategt; lt;divgt; lt;pgt;$nextTick()使用场景lt;/pgt; lt;input ref="search" v-if="isShow" type="text" placeholder="这是一个输入框" /gt; lt;button @click="search"gt;点击-立即搜索lt;/buttongt; lt;/divgt;lt;/templategt;lt;scriptgt;export default { data() { return { isShow: false, }; }, methods: { search() { this.isShow = true; this.$nextTick(() =gt; { this.$refs.search.focus(); }); }, },};lt;/scriptgt;lt;stylegt;lt;/stylegt;
[效果]:
关于Vue中$refs和$nextTick用法的详细说明,本文到此结束。更多关于Vue $refs $nextTick的信息
精彩评论