如何在没有vue路由器的情况下在搜索字段vue js上实现自动建议?

时间:2017-12-16 13:49:16

标签: vue.js vuejs2 vue-component vue-router vuex

我的观点是这样的:

<div id="app">
    <h1>Simple typeahead example</h1>
    <input placeholder="Search US states" @input="input" v-model="typeahead" />
    <ul v-if="!selected && typeahead">
      <li v-for="state in states | filterBy typeahead" @click="select(state)">{{ state }}</li>
    </ul>
</div>

我的vue组件是这样的:

new Vue({
    el: '#app',
    data: {
        selected: null,
        typeahead: null,
      states: ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
  'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
  'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
  'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
  'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
  'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
  'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
  'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
  'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']
    },

    methods: {
        select: function(state){
        this.typeahead = state
        this.selected = state
      },

      input: function(){
        this.selected = null
      }
    }
});

演示和完整代码如下:http://jsfiddle.net/oscar11/tm8k8907/10/

上面的代码有效。但它使用vue路由器

我不想使用vue路由器

没有使用vue路由器还有其他方法吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

HTML:

<li v-for="state in states" v-if="filterBySelect(state)" @click="select(state)">{{ state }}</li>

方法:

filterBySelect (value) {
    if (!this.typeahead || this.typeahead.length === 0) return true
    return value.toLowerCase().split(this.typeahead.toLowerCase()).length > 1
  }