【vue学习】vue 组件 实例 自动提示的搜索框

基于element-ui

输入内容,会自动从服务器获取建议,然后显示

 

 

 

 

主要有两个个方法

querySearchAsync,传入查询参数和一个回调函数,根据查询参数,返回一个数组,value表示提示列表显示的信息,还可以放入对象

handleSelect,当提示条目被选中时 触发,会传入,提示的对象数组,可以取出之前放入的对象,传递对象而不是对象id,可以减少查询次数

 1 <template>
 2   <div class="wrapper">
 3     <el-autocomplete size="small"
 4                      v-model="msg"
 5                      :fetch-suggestions="querySearchAsync"
 6                      placeholder="请输入内容..."
 7                      @select="handleSelect">
 8       <i slot="suffix" class="el-input__icon el-icon-close" @click="msg=''"></i>
 9     </el-autocomplete>
10   </div>
11 </template>
12  
13 <script>
14   import Vue from 'vue'
15   import {Button, Select, Input, Autocomplete} from 'element-ui'
16   import 'element-ui/lib/theme-chalk/index.css'
17   import {get_hot, search_movie} from "../api/movie_api";
18  
19   Vue.component(Button.name, Button)
20   Vue.component(Select.name, Select)
21   Vue.component(Input.name, Input)
22   Vue.component(Autocomplete.name, Autocomplete)
23  
24   export default {
25     name: "search",
26     data() {
27       return {
28         movie_list: [],
29         msg: '',
30       };
31     },
32     components: {},
33     methods: {
34       clear() {
35         console.log('clear')
36       },
37       async loadAll() {
38         let list = await get_hot()
39         // console.log('hot list', list)
40         return list
41       },
42       async querySearchAsync(queryString, cb) {
43  
44         if (this.msg.length == 0) {
45           this.movie_list = await get_hot()
46         } else {
47           this.movie_list = await search_movie(this.msg)
48         }
49         let results = []
50         for (let i of  this.movie_list) {
51           // console.log(i)
52           results.push({
53             value: i['alt_title'],
54             movie_id: i['id'],
55           })
56         }
57         cb(results)
58       },
59  
60       handleSelect(item) {
61         // console.log('点击的电影是', item['movie_id']);
62         this.$emit('change_movie_id', item['movie_id'])
63       }
64     },
65     mounted() {
66       this.movie_list = this.loadAll();
67     }
68   }
69 </script>
70  
71 <style scoped>
72  
73   .wrapper {
74     display: flex;
75     justify-content: center;
76     /*margin: 5px;*/
77   }
78  
79 </style>

 

posted @ 2022-02-17 10:41  gtea  阅读(1165)  评论(0编辑  收藏  举报