-ref和$refs获取dom和组件

95 阅读1分钟

ref、$refs和 $$nextTick

  1. 作用:利用ref和$refs可以利用获取dom元素,或组件实例

②获取组件

  1. 目标组件-添加ref属性
<BaseFrom ref="baseFrom"></BaseFrom>
  1. 恰当时机,通过this.$refs.xxx,获取目标组件就可以调用组件对象中的方法
this.$refs.baseFrom.组件方法()

为什么会用到$nextTick呢?

Vue的Dom更新是异步的,我们要获取更新后的Dom,就需要用到$nextTick

假设我们现在需求:编辑标题,编辑框自动聚焦
<template>
<div class='#app'>
    <!-- 是否在编辑状态 -->
    <div v-if="isShowEdit">
    <input ref="inp" v-model="editValue" type="text">
    <button @click="">确定</button>
    </div>
    
    <!-- 默认状态 -->
    <div vi-else>
    <span>{{title}}</span>
    <button @click="handleEdit">编辑</button>
    </div>
</div>
</template>
<script>
export default{
data(){
    return{
    title:'大标题',
    isShowEdit:false,
    editValue:''
    },
methods:{
    handleEdit(){
    //显示输入框(Dom更新异步)
    this.isShowEdit = ture
    //让输入框获取焦点
    //this.$refs.inp.focus()   (这样写法是错误的,因为Dom更新是异步,所以无法获取更新之后的输入框)
    
    //$nextTick等dom更新完成后,立刻执行函数体
    this.$nextTick(()=>{
        this.$refs.inp.focus() 
    })
    }
    
    //setTimeout()具有相同的效果,但是$nextTick更为精确好用
    
    //setTimeout(()=>{
    //this.$refs.inp.focus() 
    // },1000)
}

</script>