如何便捷给input施加focus方法?

有以下代码,获取input焦点时将光标置在右侧的,现在项目有很多地方需要用上,请问怎么快速、简单的修改

@focus="inputFocusRight($event)"

   inputFocusRight(e) {
        const editTask = e.srcElement;
        const length = editTask.value.length;
        editTask.focus();

        setTimeout(() => {
          editTask.selectionStart = length;
          editTask.selectionEnd = length;
        });
      },
阅读 1.4k
3 个回答

全局自定义指令:

// main.js 
Vue.directive('focus-right', {
  inserted: function (el) {
    el.addEventListener('focus', function () {
      const length = el.value.length;
      setTimeout(() => {
        el.selectionStart = length;
        el.selectionEnd = length;
      });
    });
  }
});

在组件里:

<input v-focus-right>

或者插件:

// focusPlugin.js
const FocusRightPlugin = {
  install(Vue) {
    Vue.prototype.$inputFocusRight = function (e) {
      const input = e.target;
      const length = input.value.length;
      setTimeout(() => {
        input.selectionStart = length;
        input.selectionEnd = length;
      });
    };
  }
};

// 在 main.js 里
import FocusRightPlugin from './focusPlugin';

Vue.use(FocusRightPlugin);

// 然后在组件里用
<input @focus="$inputFocusRight">
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

const cursor = {
  beforeMount: el => {
    el._value = el.value
  },
  updated: el => {
    if (el._value !== el.value) {
      el.setSelectionRange(el.value.length, el.value.length)
      el._value = el.value
    }
  }
}

app.directive('cursor', cursor)

app.mount('#app')
<input v-cursor @focus="inputFocusRight($event)" />

关于操作dom的功能复用,可以使用指令。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题