【发布时间】:2018-08-05 17:17:08
【问题描述】:
我正在由 Firebase 支持的 Vue.js 中构建一个自动完成菜单(使用 vue-fire)。目的是开始输入用户的显示名称,并在下面的 div 列表中显示匹配记录。
模板如下所示:
<b-form-input id="toUser"
type="text"
v-model="selectedTo"
@change="searcher">
</b-form-input>
<div v-on:click="selectToUser(user)" class="userSearchDropDownResult" v-for="user in searchResult" v-if="showSearcherDropdown">{{ user.name }}</div>
单击潜在匹配项后,目的是设置字段值并清除匹配项列表。
这是组件的代码部分:
computed: {
/* method borrowed from Reddit user imGnarly: https://www.reddit.com/r/vuejs/comments/63w65c/client_side_autocomplete_search_with_vuejs/ */
searcher() {
let self = this;
let holder = [];
let rx = new RegExp(this.selectedTo, 'i');
this.users.forEach(function (val, key) {
if (rx.test(val.name) || rx.test(val.email)) {
let obj = {}
obj = val;
holder.push(obj);
} else {
self.searchResult = 'No matches found';
}
})
this.searchResult = holder;
return this.selectedTo;
},
showSearcherDropdown() {
if(this.searchResult == null) return false;
if(this.selectedTo === '') return false;
return true;
}
},
methods: {
selectToUser: function( user ) {
this.newMessage.to = user['.key'];
this.selectedTo = user.name;
this.searchResult = null;
}
}
Typeahead 运行良好,每次更改输入字段时,都会调用 searcher() 函数并使用正确的值填充 searchResult。显示了 v-for 作品和 div 列表。
单击 div 时,我调用 selectToUser(user)。这会正确地将用户对象的详细信息报告到控制台。
但是,第一次单击时,我在控制台中出现异常,并且 div 没有清除(我希望它们消失,因为我将 searchResults 设置为 null)。
[Vue warn]: Error in event handler for "change": "TypeError: fns.apply is not a function"
found in
---> <BFormInput>
<BFormGroup>
<BTab>
TypeError: fns.apply is not a function
at VueComponent.invoker (vue.esm.js?efeb:2004)
at VueComponent.Vue.$emit (vue.esm.js?efeb:2515)
at VueComponent.onChange (form-input.js?1465:138)
at boundFn (vue.esm.js?efeb:190)
at invoker (vue.esm.js?efeb:2004)
at HTMLInputElement.fn._withTask.fn._withTask (vue.esm.js?efeb:1802)
如果我单击 div 秒 次,则没有错误,输入值已设置,div 消失。
所以我怀疑向 this.selectedTo 写入一个值(这也是元素的 v-model 对象正在触发 @change 事件。在第二次单击时,值实际上并没有改变,因为它已经设置了,所以没有调用 searcher() 也没有错误。
我注意到如果元素失去焦点也会发生这种情况。
问题:通过方法更改 v-model 值时如何防止 @change 事件?
(其他信息:根据 package.json 我在 vue 2.5.2)
【问题讨论】:
标签: vuejs2