如何便捷给input施加focus方法?-灵析社区

momo

有以下代码,获取input焦点时将光标置在右侧的,现在项目有很多地方需要用上,请问怎么快速、简单的修改 @focus="inputFocusRight($event)" inputFocusRight(e) { const editTask = e.srcElement; const length = editTask.value.length; editTask.focus(); setTimeout(() => { editTask.selectionStart = length; editTask.selectionEnd = length; }); },

阅读量:12

点赞量:0

问AI
全局自定义指令: // 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; }); }); } }); 在组件里: 或者插件: // 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); // 然后在组件里用