gpt4 book ai didi

javascript - 组件自动完成 VueJS

转载 作者:行者123 更新时间:2023-12-03 01:43:17 26 4
gpt4 key购买 nike

我想创建一个自动完成组件,所以我有以下代码。

<Input v-model="form.autocomplete.input" @on-keyup="autocomplete" />
<ul>
<li @click="selected(item, $event)" v-for="item in form.autocomplete.res">
{{item.title}}
</li>
</ul>

autocomplete(e){
const event = e.path[2].childNodes[4]

if(this.form.autocomplete.input.length > 2){
this.Base.get('http://localhost:3080/post/search/post', {
params: {
q: this.form.autocomplete.input
}
})
.then(res => {
this.form.autocomplete.res = res.data

if(this.form.autocomplete.res.length > 0)
event.style.display = 'block'
})
}
},
selected(item, e){
this.form.autocomplete.item = item
console.log(e)
}

但是,在主文件中选择我的项目后如何获得返回?例如:

Home.vue

<Autocomplete :url="www.url.com/test" />

自动完成中选择我想要的项目时,如何从中获取返回并将其存储在该文件中,就像我使用v-model一样?

最佳答案

Vue Guide说:

Although a bit magical, v-model is essentially syntax sugar forupdating data on user input events, plus special care for some edgecases.

然后在Vue Using v-model in Components ,

the <input> inside the component must:

Bind the value attribute to a value prop
On input, emit its own custom input event with the new value

然后按照上面的指南,一个简单的演示如下:

Vue.config.productionTip = false

Vue.component('child', {

template: `<div>
<input :value="value" @input="autocomplete($event)"/>
<ul v-show="dict && dict.length > 0">
<li @click="selected(item)" v-for="item in dict">
{{item.title}}
</li>
</ul>
</div>`,
props: ['value'],
data() {
return {
dict: [],
timeoutControl: null
}
},
methods: {
autocomplete(e){
/*
const event = e.path[2].childNodes[4]

if(this.form.autocomplete.input.length > 2){
this.Base.get('http://localhost:3080/post/search/post', {
params: {
q: this.form.autocomplete.input
}
})
.then(res => {
this.form.autocomplete.res = res.data

if(this.form.autocomplete.res.length > 0)
event.style.display = 'block'
})
}*/
clearTimeout(this.timeoutControl)
this.timeoutControl = setTimeout(()=>{
this.dict = [{title:'abc'}, {title:'cde'}]
}, 1000)
this.$emit('input', e.target.value)
},
selected(item){
this.selectedValue = item.title
this.$emit('input', item.title)
}
}
})

new Vue({
el: '#app',
data() {
return {
testArray: ['', '']
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="app">
<child v-model="testArray[0]"></child>
<child v-model="testArray[1]"></child>
<div>Output: {{testArray}}</div>
</div>

关于javascript - 组件自动完成 VueJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50749176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com