组件自动完成VueJS

时间:2018-06-07 19:48:39

标签: javascript vue.js

我想创建一个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一样?

1 个答案:

答案 0 :(得分:1)

正如Vue Guide所说:

  

虽然有点神奇,但v-model基本上是语法糖   更新用户输入事件的数据,以及对某些边缘的特殊照顾   例。

然后在Vue Using v-model in Components

  

组件内的<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>