1. 程式人生 > 實用技巧 >Vue+Element 實現 模糊搜尋

Vue+Element 實現 模糊搜尋

首先,npm安裝Element,然後匯入

html 中

<el-autocomplete v-model="searchtext" size="mini" :fetch-suggestions="querySearchGroup" @select="selectGroup"
                     @input="groupListMe" placeholder="請輸入準確的企業全稱"></el-autocomplete>

JS 中

data() {
            return {
                groupArr: [],
                groupList: [{
                    companyName: 
'', userId: '' }], searchtext: '' }; },
watch: {
            'searchtext': {
                deep: true,
                handler: function(newVal, oldVal) {
                    this.groupArr = []; //這是定義好的用於存放下拉提醒框中資料的陣列
                    var
len = this.groupList.length; //groupList var arr = []; for (var i = 0; i < len; i++) { //根據輸入框中的值進行模糊匹配 if (this.groupList[i].companyName.indexOf(this.searchtext) >= 0) { arr.push({ value:
this.groupList[i].companyName, id: this.groupList[i].userId }) } } this.groupArr = arr } }, },
methods: {
        groupListMe() {
            let _this = this
            axios.get(ApiInfo._url + '/api/company/query-company?keyword=' + _this.searchtext).then(function(res) {
                if (res.data.code == 200) {
                    _this.groupList = []
                    _this.groupArr = []
                    _this.groupList = res.data.content.list
                    for (let item of _this.groupList) {
                        _this.groupArr.push({
                            value: item.companyName,
                            id: item.userId
                        })
                    }
                }
            })
        },
        querySearchGroup(queryString, cb) {
            var groupArr = this.groupArr;
            cb(groupArr);
        },
        selectGroup(val) {
            this.groupId = val.id
        }
    }