Vue 中如何让 input 聚焦?(包含视频讲解)

做者:Michael Thiessen前端

译者:前端小智vue

来源:laracasts.comgit

点赞再看,养成习惯github

本文 GitHub github.com/qq449245884… 上已经收录,更多往期高赞文章的分类,也整理了不少个人文档,和教程资料。欢迎Star和完善,你们面试能够参照考点复习,但愿咱们一块儿有点东西。面试

本人对这节录了视频讲解,欢迎点击:www.ixigua.com/i6790914892…浏览器

在作项目时,有时咱们须要让 input 聚焦,为了让用户更好的使用。微信

让 input 聚焦

全部的浏览器都有一个内置的方法,让 input 聚焦。首先,咱们须要获取元素。工具

在原生 JS 中,咱们可使用下面方式来获取元素:this

<form>
  <input id="email" />
</form>

const input = document.getElementById('email');
复制代码

Vue 提供了一个更好的方法:spa

<template>
  <input ref="email" />
</template>

const input = this.$refs.email;    
复制代码

获取元素后,咱们就可让 input 聚焦了

<template>
  <input ref="email" />
</template>

export default {
  methods: {
    focusInput() {
      this.$refs.email.focus();
    }
  }
}
复制代码

若是使用的是自定义组件,则$ref获取是该组件,而不是咱们基础元素。 所以,若是尝试让该组件聚焦,就会报错。要得到自定义组件的根元素,咱们能够用 $el 访问:

<template>
  <CustomInput ref="email" />
</template>
    
import CustomInput from './CustomInput.vue';

export default {
  components: {
    CustomInput,
  },
  methods: {
    focusInput() {
      this.$refs.email.$el.focus();
    }
  }
}
复制代码

可是,若是要在组件加载时就聚焦,要怎么作呢?

页面加载时聚焦

咱们能够 mouted 生命周期,让元素聚焦:

import CustomInput from './CustomInput.vue';

export default {
  components: {
    CustomInput,
  },
  mounted() {
    this.focusInput();
  },
  methods: {
    focusInput() {
      this.$refs.email.$el.focus();
    }
  }
}
复制代码

等待从新渲染

在某些状况下,咱们可能须要等待Vue完成整个应用程序的从新渲染。例如,若是将input从隐藏状态切换到显示状态。

所以咱们须要等待 input 加载好后,才能从新聚焦。

<template>
  <div>
    <CustomInput v-if="inputIsVisible" ref="email" />
  </div>
</template>

import CustomInput from './CustomInput.vue';

export default {
  components: {
    CustomInput,
  },
  data() {
    return {
      inputIsVisible: false,
    };
  },
  mounted() {
    this.focusInput();
  },
  methods: {
    showInput() {
      // Show the input component
      this.inputIsVisible = true;

      // Focus the component, but we have to wait
      // so that it will be showing first.
      this.nextTick(() => {
        this.focusInput();
      });
    },
    focusInput() {
      this.$refs.email.$el.focus();
    }
  }
}
复制代码

这里,咱们在 nextTick 方法中调用 focusInput 方法。由于 nextTick 中表示 Dom 已经加载完成了,因此这时咱们才能获取到 input 元素。


代码部署后可能存在的BUG无法实时知道,过后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给你们推荐一个好用的BUG监控工具 Fundebug

原文:laracasts.com/discuss/cha…


交流

文章每周持续更新,能够微信搜索「 大迁世界 」第一时间阅读和催更(比博客早一到两篇哟),本文 GitHub github.com/qq449245884… 已经收录,整理了不少个人文档,欢迎Star和完善,你们面试能够参照考点复习,另外关注公众号,后台回复福利,便可看到福利,你懂的。

相关文章
相关标签/搜索