
便捷给 input 施加 focus 方法
在 Vue.js 中,需要在输入框获取焦点时将光标置于右侧。以下几种方式可以快速便利地解决此问题:
自定义指令
// 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">
登录后复制
以上就是如何在 Vue.js 中便捷地将输入框焦点置于右侧?的详细内容,更多请关注米云其它相关文章!
