如何便捷给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;
});
},
回答:
全局自定义指令:
// 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.jsconst 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的功能复用,可以使用指令。
以上是 如何便捷给input施加focus方法? 的全部内容, 来源链接: utcz.com/p/935100.html