首页 > 解决方案 > 组件自动完成 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

标签: javascriptvue.js

解决方案


正如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>


推荐阅读