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