简体   繁体   English

通过单击外部 vue 重置自动完成字段文本

[英]reset autocomplete field text by clicking outside vue

I have an autocomplete field.我有一个自动完成字段。 If i put any text and it matches the result set then it will populate the dropdown result.如果我输入任何文本并且它与结果集匹配,那么它将填充下拉结果。 If it doesn't match anything then by clicking outside it will reset the input field forcefully.如果它不匹配任何内容,则通过单击外部它将强制重置输入字段。

So, for this approach i have created the vue click outside directive因此,对于这种方法,我创建了 vue click outside 指令

    import Vue from 'vue';

const nodeList = [];
const ctx = '@@clickoutsideContext';

let startClick;
const counter = 0;

const isServer = Vue.prototype.$isServer;

/**
 * added this on event function for direct dom manipulation
 */
const onEvent = (function() {
    if (!isServer && document.addEventListener) {
        return function(element, event, handler) {
            if (element && event && handler) {
                element.addEventListener(event, handler, false);
            }
        };
    }
    return function(element, event, handler) {
        if (element && event && handler) {
            element.attachEvent(`on${event}`, handler);
        }
    };
})();

!isServer &&
    onEvent(document, 'mousedown', e => {
        startClick = e;
    });

!isServer &&
    onEvent(document, 'mouseup', e => {
        nodeList.forEach(node => node[ctx].documentHandler(e, startClick));
    });

// setting up mouse events

function createDocumentHandler(el, binding, vnode) {
    return function(mouseup = {}, mousedown = {}) {
        if (
            !vnode ||
            !vnode.context ||
            !mouseup.target ||
            !mousedown.target ||
            el.contains(mouseup.target) ||
            el.contains(mousedown.target) ||
            el === mouseup.target ||
            (vnode.context.popperElm &&
                (vnode.context.popperElm.contains(mouseup.target) ||
                    vnode.context.popperElm.contains(mousedown.target)))
        )
            return;

        if (
            binding.expression &&
            el[ctx].methodName &&
            vnode.context[el[ctx].methodName]
        ) {
            vnode.context[el[ctx].methodName]();
        } else {
            el[ctx].bindingFn && el[ctx].bindingFn();
        }
    };
}

/**
 * v-clickoutside
 * @desc Only trigger when click outside
 * @example
 * ```vue
 * <div v-element-clickoutside="handleClose">
 * ```
 */
export default {
    bind(el, binding, vnode) {
        nodeList.push(el);
        const id = counter + 1;
        el[ctx] = {
            id,
            documentHandler: createDocumentHandler(el, binding, vnode),
            methodName: binding.expression,
            bindingFn: binding.value
        };
    },

    update(el, binding, vnode) {
        el[ctx].documentHandler = createDocumentHandler(el, binding, vnode);
        el[ctx].methodName = binding.expression;
        el[ctx].bindingFn = binding.value;
    },

    unbind(el) {
        const len = nodeList.length;

        for (let i = 0; i < len; i += 1) {
            if (nodeList[i][ctx].id === el[ctx].id) {
                nodeList.splice(i, 1);
                break;
            }
        }
        delete el[ctx];
    }
};

Here is the autocomplete field in forms field这是 forms 字段中的自动完成字段

<div v-if="field.type == 'autocomplete'">
                <vu-auto-complete
                    v-model="fieldvalues[field.key]"
               :items="formFieldAutocompleteItems[fieldvalues[field.key]] || []"
                    :label="labelrequired(field)"
                    :placeholder="field.placeholder"
                    :error-message="errorMsg[field.key]"
                    @input="handleOnInput($event, field)"
                    @selected="getSelectedData($event, field)"
                >
                </vu-auto-complete>
            </div>

methods for handleOnInput handleOnInput 的方法

handleOnInput(inputKey, field) {
        if (inputKey !== null && inputKey.length >= 3) {
            this.fieldvalues = {
                ...this.fieldvalues,
                [field.key]: inputKey
            };
            const data = {
                url: field.autocompleteUri,
                search: field.autocompleteUriKey,
                text: inputKey,
                key: field.key
            };
            clearTimeout(this.timer);
            this.timer = setTimeout(() => {
                this.$emit('autocompleteInput', data);
            }, 500);
        } else if (inputKey.length === 0 || inputKey === null) {
            const formData = { ...this.fieldvalues };
            if (field.dependentFields && field.dependentFields.length > 0) {
                for (let i = 0; i < field.dependentFields.length; i += 1) {
                    formData[field.dependentFields[i]] = '';
                }
            }
            this.fieldvalues = formData;
        }
    },

Autocomplete field is working fine.自动完成字段工作正常。 So, i need directive or methods to reset any input by clicking outside.所以,我需要指令或方法来通过点击外部来重置任何输入。

Any suggestions or examples will be helpful to understand.任何建议或示例都将有助于理解。

I'd suggest you use the onClickOutside utility from VueUse.我建议您使用 VueUse 的onClickOutside实用程序。

VueUse is effectively a collection of super useful utility functions for Vue with support for Vue2, Vue3 and Typescript. VueUse 实际上是 Vue 超级有用的实用程序功能的集合,支持 Vue2、Vue3 和 Typescript。

There's over 90 different utilities for so many different use cases and the library is treeshakable so you only have to bundle what you use.对于这么多不同的用例,有超过 90 种不同的实用程序,并且该库是可摇树的,因此您只需捆绑您使用的内容。

The onClickOutside utility expects a target ref and a callback along with an optional third param for configuration. onClickOutside实用程序需要一个目标ref和一个回调以及可选的第三个配置参数。

Something like this should work for you:像这样的东西应该适合你:

onClickOutside(
  inputRef,
  (event) => {
    console.log(event);
    this.inputText = '';
  },
  { event: 'mousedown' },
)

This saves you the time of writing custom code where you may miss out on important considerations such as accessibility.这可以节省您编写自定义代码的时间,因为您可能会错过重要的考虑因素,例如可访问性。 If you want, you can dig into the source of the utility and explore how it works internally.如果需要,您可以深入研究该实用程序的源代码并探索其内部工作原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在鼠标按下/输入时重置文本字段 - jQuery UI 自动完成 - Reset text field on Mouse press / Input - jQuery UI Autocomplete MSIE:单击外部时将焦点保持在文本字段中 - MSIE: Keep focus in text field when clicking outside of it 单击 DIV 外部时重置评级 - Reset rating when clicking outside of the DIV Vuetify <v-text-field> 单击Google Maps自动完成的结果后清除输入 - Vuetify <v-text-field> clears input after clicking on result from Google Maps autocomplete 有没有办法通过单击外部来关闭 vue 组件? - Is there a way to close a vue component by clicking outside of it? 如何在菜单外添加单击按钮以打开新的文本字段,而不是单击“其他”? - How do I add a click button outside the menu to open a new text field instead of clicking on “other”? 再次单击该按钮以重置字段 - clicking the button again making the field reset jQuery自动完成功能-防止在外部div上单击时将其关闭? - jquery autocomplete - prevent closing it when clicking on outside div? 通过单击按钮jquery设置和重置文本 - Set and reset text by clicking button jquery 在模态窗口外部单击时重置Bootstrap模态 - Reset Bootstrap modal when clicking outside modal window
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM