vue-this.$nextTick(cb)

this.$nextTick(cb)
cb- - -回调函数,
当页面再次渲染完成后,执行cb回调函数

使用示例:
点击按钮后显示输入框,并且输入框显示时自动获取焦点

代码:

<template>
  <div>
    <h1>APP根组件</h1>
    <input v-if="isVisiable" type="text" ref="inp">
    <button v-else @click="showInp">点击隐藏按钮,显示输入框</button>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      isVisiable: false
    }
  },
  methods: {
    showInp() {
      this.isVisiable = true
      // this.$refs.inp.focus()  直接这样写会报错
      this.$nextTick(() => {
        // console.log(this.$refs.inp);
        this.$refs.inp.focus()
      })
    }
  }
}
</script>

image.png

this. r e f s . i n p . f o c u s ( ) 获 取 焦 点 操 作 要 放 在 t h i s . refs.inp.focus() 获取焦点操作要放在 this. refs.inp.focus()this.nextTick(cb) 方法中,
因为页面的渲染是异步操作的,当执行 this.isVisiable = true 后,如果立即执行this. r e f s . i n p . f o c u s ( ) , 此 时 页 面 还 没 有 渲 染 出 i n p u t 输 入 框 , 获 取 不 到 该 元 素 , 所 以 会 报 错 , 将 获 取 焦 点 操 作 放 入 t h i s . refs.inp.focus(),此时页面还没有渲染出 input 输入框,获取不到该元素,所以会报错, 将获取焦点操作放入 this. refs.inp.focus()inputthis.nextTick() 函数中后,页面渲染完成后才会执行里面的代码,渲染完成后就有input元素了,所以就可以执行input元素的操作了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值