ref,refs,和$nextTick

ref和refs的用法:详情看

(9条消息) vue中用$ref和$refs写出像js一样的this遍历样式_m0_64207574的博客-CSDN博客_refs遍历

$nextTick

$nextTick(()=>{})监听dom是否更新后执行的回调函数方法

执行思路,由于mvvm模式的特点,视图层改变引起数据源改变,重新引起页面渲染,但是在重新渲染的过程中会发现 input处于if为false的状态,会报错,所以要使用$nextTick方法监听

这里是监听了input这个dom元素是否发生改变;发生改变后再执行$nextTick里的方法;

此方法类似于ES6中的promise;异步执行同步处理

如:

<template>
  <div>
    <input
      type="text"
      placeholder="输入要搜索的关键字"
      v-if="isShow"
      ref="inp"
    />
    <button v-else @click="searchFn">
      点击搜索,出输入框并马上处于激活状态
    </button>
  </div>
</template>

<script>
export default {
  name: "Next",
  data() {
    return {
      isShow: false,
    };
  },
  methods: {
    searchFn() {
      this.isShow = true; // 点击显示输入框, 隐藏按钮
      this.$refs.inp.focus();
      // 让输入框处于激活状态

      // 发现报错了, this.$refs.inp是个undefined(没获取到dom标签)
      // 因为数据isShow改变后, "异步"显示input, 渲染组件需要时间,并且时间没有JS执行的快;所以获取不到,而代码会继续往下走所以还没获取到input, 所以是undefined

      // 解决: 在dom更新后, 会触发$nextTick里的回调函数
      this.$nextTick(() => {
        this.$refs.inp.focus();
      });
    },
	//方法2
    // async searchFn() {
    // 	this.isShow = true
    // 	await this.$nextTick()
    // 	this.$refs.inp.focus()
    // },
 /  方法3
    // searchFn() {
	// 	this.isShow = true; 
    //   setTimeout(() => {
    //     this.$refs.inp.focus();
    //   }, 0);
    // },
  },
};
</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值