目录
ref和$refs
$nextTick 异步更新
ref和$refs
1.作用
利用ref 和$refs可以用于获取dom元素或组件实例
2.特点
查找范围→当前组件内(更精确稳定)
3.语法
1.给要获取的盒子添加ref属性
<div ref="chartRef">我是渲染图表的容器</div>
⒉.获取时通过$refs获取this.$refs.chartRef 获取
mounted ({console.log(this. $refs.chartRef)
}
4.注意
之前只用document.querySelect('.box')获取的是整个页面中的盒子
获取dom元素
要获取谁的dom元素,就在谁的标签内加上 ref=’ ‘
ref也是组件通信的一中方法
拿到dom元素是在挂载后,mounted
{ref属性值: ref属性所在的dom或组件}
ref可以拿到组件属性和方法
例:App.vue
<template><div><p ref="pRef">晨起开门雪满山,雪晴云淡日光寒。</p><button @click="fn">按钮</button></div>
</template><script>
export default {methods: {fn () {console.log(this.$refs.pRef)}}
}
</script><style></style>
$nextTick 异步更新
$nextTick:等DOM更新后,才会触发执行此方法里的函数体
语法: this.$nextTick(函数体)
this . $nextTick(() =>{this.$refs.inp.focus()
}
注意: $nextTick内的函数体一定是箭头函数,这样才能让函数内部的this指向Vue实例
数据改变---->dom更新,需要时间->等待dom更新完毕操作dom
原理:promise.then------>MutationObserver----->setImmediate---->setTimeout
App.vue
<template><div><button @click="fn">按钮</button><input type="text" v-show="isShow" ref="textRef"></div>
</template><script>export default {name: 'AppComp',data () {return {isShow: false}},methods: {fn () {console.log(this.$refs.textRef)this.$nextTick(() => {this.$refs.textRef.focus()this.isShow = true})}}
}
</script><style></style>