我正在尝试使用v-model在Vue的输入中设置值。我正在使用Vue Typeahead库。我遇到的问题是,当我点击我要选择的项目时,我会触发Onhit方法,在此方法中,我更改查询的值以更新输入值。在Onhit()方法中,这不起作用,但如果我在created()方法中更改它,它将会改变。
我可以确认当我在console.log()this.query时获取新值。它只是没有动态更新。
<template>
<div>
<div class="input-group">
<input type="text"
class="form-control"
autocomplete="off"
v-model="query"
@keydown.down="down"
@keydown.up="up"
@keydown.enter="hit"
@keydown.esc="reset"
@blur="reset"
@input="update"
v-bind:placeholder="selectedLocation"/>
<span class="input-group-addon">
<i class="fa fa-spinner fa-spin" v-if="loading"></i>
<template v-else>
<i class="fa fa-search" v-show="isEmpty"></i>
<i class="fa fa-times" v-show="isDirty" @click="reset"></i>
</template>
</span>
</div>
<!-- the list -->
<ul v-show="hasItems">
<li v-for="(item, $item) in items" :class="activeClass($item)" @mousedown="hit" @mousemove="setActive($item)">
<span v-html="item.city"></span>
<div class="meta-location-data"><span v-html="item.region"></span><span>, </span><span v-html="item.country"></span></div>
</li>
</ul>
</div>
</template>
<script>
import VueTypeahead from 'vue-typeahead';
export default {
extends: VueTypeahead,
props: ['selectedLocation'],
create() {
// This works
this.query = 'test';
}
data () {
return {
// The source url
// (required)
src: '/api/test/',
// The data that would be sent by request
// (optional)
data: {},
// Limit the number of items which is shown at the list
// (optional)
limit: 5,
// The minimum character length needed before triggering
// (optional)
minChars: 3,
// Highlight the first item in the list
// (optional)
selectFirst: false,
// Override the default value (`q`) of query parameter name
// Use a falsy value for RESTful query
// (optional)
queryParamName: false
}
},
methods: {
// The Item that the user clicks on (required)
onHit (item) {
// This does not work :(
this.query = item.city;
this.$emit('location-was-changed', item);
},
// The callback function which is triggered when the response data are received (optional)
prepareResponseData (data) {
let testData = [{
city: 'Zamin Sukhteh',
region: 'Khuzestan',
country: 'Iran'
},
{
city: 'Azreh-ye ‘Abbasabad',
region: 'Khuzestan',
country: 'Iran'
},
{
city: 'Avondale',
region: 'Auckland',
country: 'New Zealand'
},
{
city: 'Elsio',
region: '',
country: 'Fiji'
}];
return testData
.filter((location) => {
// Just get the data we want
return location.country.includes(this.query)
|| location.city.includes(this.query)
|| location.region.includes(this.query)
});
}
}
}
</script>
<style scoped src="./typeahead.scss"></style>
答案 0 :(得分:0)
发现问题,vue-typeahead库在onhit触发后调用reset函数,将查询重置为null。
您可以通过添加
来解决此问题reset: function reset() {
this.items = [];
this.loading = false;
}
到你的方法(它会覆盖默认方法)。您也可以为v模型分配不同的变量。