脚本宝典收集整理的这篇文章主要介绍了vuejs里怎么获取dom,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
vuejs获取dom的方法:1、在组件的DOM部分,任意标签中写上“ref="xxx"”;2、通过组件对象“this.$refs.xxx”获取到元素即可。
本文操作环境:windows7系统、vue2.9.6版,DELL G3电脑。
Vue.js实例学习:获取DOM元素
在Vue中获取DOM元素,我们可以用ref
。
用法(和React一样):
(1)在组件的DOM部分,任意标签中 写上:ref="xxx"
(2)通过组件对象 this.$refs.xxx
获取到元素
<div id="app"></div> <script tyPE="text/javascript"> let App = { template: ` <div> <button ref="BTn">我是按钮</button> </div>`, beforeCreate() { //这里不能操作数据 console.LOG('beforeCreate: ', this.$refs.btn); }, created() { //这里可以操作数据了 console.log('created: ', this.$refs.btn); }, beforemount() { //new Vue 发生装载, 替换 <div id="app">之前 console.log('beforeMount: ', this.$refs.btn); }, mounted() { //装在数据之后 console.log(';mounted: ', this.$refs.btn); }, }; new Vue({ el: '#app', components: { app: App }, template: `<app />`, }); </script>
控制台输出:
<div id="app"></div> <script type="text/javascript"> let Temp = { template: ` <div>我是子组件</div> `, }; let App = { components: { temp: Temp, }, template: `<temp ref="tmp"/>`, mounted() { console.log(this.$refs.tmp); }, }; let vm = new Vue({ el: '#app', components: { app: App }, template: `<app />`, }); </script>
控制台输出:
输出
的是
temp组件
。假如我们把console.log(this.$refs.tmp)改为:
console.log(this.$refs.tmp.$el);
控制台会输出下图,由此可知 $el 代表着什么~
要求:在显示input元素的瞬间,获取input的焦点
<div id="app"></div> <script type="text/javascript"> let App = { template: ` <div> <input type="text" v-if="isShow" ref="myInput" /> </div>`, data() { return { isShow: false, }; }, mounted() { this.isShow = true; //显示input元素 this.$refs.myInput.focus(); //获取input的焦点 }, }; let vm = new Vue({ el: '#app', components: { app: App }, template: `<app />`, }); </script>
运行后报错:
this.$refs.myInput
也是undefined,为什么ref没获取到DOM元素呢?我们先思考,如果我们把mounted函数内改成:
mounted() { this.isShow = true; this.isShow = false; this.isShow = true; },
运行过程中,input元素会 先显示,再消失,然后再显示吗?
答案是否定的。因为Vue会先让代码执行完,然后才会根据最终的值,进行DOM操作。
其实上面的代码等同于下面的代码:
mounted() { this.isShow = true; },
那么怎么解决呢?
这里我们用 $nextTick
解决~
什么时候用:在Vue渲染DOM到页面后 立即做某件事,用$nextTick
this.$nextTick(function() { ·····DOSomething })
let App = { template: ` <div> <input type="text" v-if="isShow" ref="myInput" /> </div>`, data() { return { isShow: false, }; }, mounted() { //显示input元素的瞬间,获取焦点 this.isShow = true; this.$nextTick(function() { this.$refs.myInput.focus(); }); }, }; let vm = new Vue({ el: '#app', components: { app: App }, template: `<app />`, });
推荐学习:《最新的5个vue.js视频教程精选》
以上就是vuejs里怎么获取dom的详细内容,更多请关注脚本宝典其它相关文章!
以上是脚本宝典为你收集整理的vuejs里怎么获取dom全部内容,希望文章能够帮你解决vuejs里怎么获取dom所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。