vue中實現一個搜索框的組件

在前端開發中有些東西就會經常反覆使用,這樣的東西抽取成組件比較合適,最近工作中遇到一個搜索樓盤的頁面需要反覆多次使用,抽取成了組件,現在記錄一下

1.創建一個searchcom.vue文件

2.文件中填入一下代碼,具體內容在代碼後邊進行解釋

<template>
<div>
    <header class="page-header">
        <div class="searchwrap border-bottom">
            <div class="searchbox">
                <span class="icon-search"><img :src="images.searchpng" alt=""></span>
                <input type="text" class="input-search" v-model="keyword" id="searchTxt" ref="searchTxt" placeholder="請輸入樓盤名稱" filterable  value="">
                <span class="search-x"><img :src="images.searchxpng" alt="" @click="clearInput"></span>
            </div>
        <span class="quxiao" style="display:block;" @click="cancel">取消</span>
    </div> 
    </header>
    
    <div class="page-container mt44">
      <div class="stafflist" >
          <ul>
            <li class="clearfix" v-for="(project,index) in searchData" :key="index" @click="selectProject(project)">
              <div class="staffinfo">
                <div class="s-desc">
                  <h2>{{project.projname}} <span v-if="project.aliasprojname!=''" class="f13">({{project.aliasprojname}})</span></h2>
                  <p>{{project.district}} {{project.comarea}}</p>
                </div>
              </div>
            </li>      
          </ul>
        </div>          
    </div>
    <div class="mask" style="display:none"></div>
</div>


</template>

<script>
    import {Toast, Indicator} from 'mint-ui';
    import axiosService from '@/pages/wap/api/axiosservice.js';
    export default {
        props : {
            city : String
        },
        data() {
            return {
                searchData:[],
                keyword : '',
                images: {
                    searchpng:require('@/pages/wap/assets/images/search.png'),
                    searchxpng:require('@/pages/wap/assets/images/search-x.png')
                }
            }
        },
        watch : {
            'keyword' : function(newVal,oldVal){
                this.getSearchProjects(newVal)
            }
        },
        methods:{
            cancel(){
                this.$emit('cancelSearch');
            },
            clearInput(){
                this.keyword='';
            },
            selectProject(project){ //選擇樓盤
                this.$emit('selectProject',project);
            },
            getSearchProjects(keyword){
                //搜索樓盤
                Indicator.close();
                var currentTime = new Date().getTime();
                this.newcodeSearchTime = currentTime;
                setTimeout(() => {
                    if (this.newcodeSearchTime == currentTime) {
                        var searchparm = { keyword: keyword,city:this.city };
                        this.newcodeSearchTime = currentTime;
                        this.addTip= '';
                        axiosService({
                            url: process.env.VUE_APP_apiHost+'/project/getSearchProjects',
                            method: 'get',
                            params: searchparm
                        }).then(res => {
                            if (res != null && res.data != null) {
                                if (res.status === 1) {
                                    this.searchData = res.data;
                                } else {
                                    Toast({
                                        message: res.message,
                                        duration: 2000
                                    });
                                }
                            }
                        }).catch(err => {
                            Toast({
                                message: err,
                                duration: 2000
                            });
                            this.isLoading = false;
                        });
                    }
                }, 300);
            }
        }
    }
       
</script>

<style scoped>

</style>

template 裏邊是html的內容

其中

    import {Toast, Indicator} from 'mint-ui';

    import axiosService from '@/pages/wap/api/axiosservice.js';

是分別引入移動h5需要的組件和調取接口的文件,

props中數據是需要從調用組件時傳入的參數或者叫做數據,一般最好是指定類型

watch裏邊的keyword是要監控數據keyword的變化,其中的兩個參數一個是原來的值,一個是變化後的新值

不管是watch還是methods中的方法,如果有些方法操作不是共用的,需要調用的地方進行單獨的處理則可以使用this.$emit('cancelSearch');  或者帶參數形式 this.$emit('selectProject',project); 交給調用的地方進行完成

cancelSearch 和selectProject 都是方法名,在調用的地方需要完成這兩個方法,project是方法中傳遞過父組件的數據

調用的地方代碼書寫形式

 

將代碼粘貼到這裏,方便以後複製

 <searchcom :city="userInfo.city" @selectProject="selectProject" @cancelSearch="cancelSearch" v-if="searchShow" ></searchcom>

components: {

           searchcom  //如果需要引入多個組件用,隔開就行

 },

          cancelSearch(){

                this.searchShow=false;

            },

            selectProject(project){

                var addparm={

                    orderId:this.$route.query.orderId,

                    newCode:project.newcode,

                    projName:project.projname,

                    city:project.city,

                    propertyType:project.purpose,

                    district:project.district,

                    comarea:project.comarea,

                    otherProjName:project.aliasprojname

                }

                this.addProj(addparm);

            },

axiosservice.js代碼也分享一下,如下

// 創建axios實例
import axios from 'axios';
const service = axios.create({
    // baseURL:process.env.NODE_ENV === 'development' ? '/rawapi' : process.env.VUE_APP_apiHost.replace("/esfapi",''),
    timeout: 5000, // 請求超時時間
    withCredentials: true
});

service.interceptors.request.use(
    config => {
        return config;
    },
    error => {
        // Do something with request error
        console.error(error); // for debug
        Promise.reject(error);
    }
);

service.interceptors.response.use(
    response => {
         return response.data;
    },
    error => {
        let message = '請求異常';
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') > -1) {
            message = '請求超時';
        }
        if (error.response) {
            let errorMessage = null;
            if (error.response.data && error.response.data.message ) {
                errorMessage = error.response.data.message;
            }
            if (errorMessage) {
                message = errorMessage;
            }
        }
        return {
            status:0,
            message:message
        };
    }
);
export  default  service;

最後的實現效果如下:

點擊添加樓盤顯示出搜索組件,輸入搜索內容展示出搜索到的樓盤列表選擇樓盤列表中的一項之後添加到列表中,添加的操作就是在上邊的selectProject方法中,搜索樓盤的接口調用是放到了組件裏,如果搜索樓盤接口不是在組件中也可以用this.$emit('搜索方法名稱',參數);交給調用端完成

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章