javascript - 组件自动完成 VueJS
问题描述
我想创建一个autocomplete
组件,所以我有以下代码。
<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" />
从我的 中选择我想要的项目时,我autocomplete
如何从中获得回报并将其存储在该文件中,就好像我正在使用一样v-model
?
解决方案
正如Vue 指南所说:
虽然有点神奇,但 v-model 本质上是用于更新用户输入事件数据的语法糖,并特别注意一些边缘情况。
然后在Vue 在 Components 中使用 v-model,
组件内部
<input>
必须: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>
推荐阅读
- node.js - How to use Facebook's Flow with Express/Sails
- java - 方法返回正确的值,但如果循环没有相应地采取行动
- asp.net - how to insert multiple rows database in asp.net core 2.1
- r - How to knit a nested choice in RMarkdown?
- python - 如何在 PyCharm 中运行命令而无需运行整个脚本?
- julia - 如何在 Julia 的函数中返回不同的东西
- python - Python添加时间限制并检查他们是否已经行动
- docker - 如何在主机上以确切用户身份运行 docker 容器?
- python - 我们可以用 python 更改对话流实现设置吗?
- android - Jitpack 不构建项目