1. 程式人生 > 實用技巧 >vue的mescroll搜尋運用以及各種填坑處理

vue的mescroll搜尋運用以及各種填坑處理

父元件處理:

<template>
       <div class="wrap">
            <!-- 搜尋框 -->
            <div class="searchInputArea">
                <div class="searchBarBox">
                    <div class="inputWrap" >
                        <form onsubmit="JavaScript:return false" action>
                            <input :placeholder = "placeholderStr" type="search" ref = "input" v-model="keyword"  />
                            <span class="clearBtn" v-show="keyword" @click="clear"></span>      
                        </form>   
                    </div> 
                </div>
            </div>  
            <div class="myFastChoiceBlock" v-show="!keyword">      
                <!-- 最近夥伴和我的關注 -->
                <fast-choice :successInvite="successInvite" @invite="inviteClick"></fast-choice>
            </div>   
            <div class="searchContainer">           
                <search-content :searchName="keyword" :successInvite="successInvite" @inviteClick="inviteClick" v-if="keyword !== ''"></search-content>
            </div>
             <!-- 協議彈出層 -->
            <pop-up @change="closeLayer" v-if="popuShow">
                <h2 class="title">{{protocolTitle}}</h2>
                <div class="content" v-html
="protocolCon"></div> <div class="confirmBtn" :class="{active:isActive}" @click="confirmProtocol">{{btntxt}}</div> <div class="popCloseCon" @click="closeActionClick"></div> </pop-up> <!-- 比例彈出層 --> <scale @change="closeScale" @send="sendAjaxClick" :number="scaleCount" :scaleBtn="scaleBtn" :scaleDesc="scaleDesc" v-show="isScale" :userId="userId"></scale> </div> </template> <script> import FastChoice from './components/fastChoice'; import PopUp from './components/PopUp'; import scale from './components/scale'; import SearchContent from './components/searchContent'; const
pageSize=10; let t=''; export default { name: "Search", data() { return { placeholderStr: '搜一搜你想找的TA', keyword: '', list: [], timerKey: null, dataList:[],//列表資料 totalPage:1, popuShow:false,//協議彈出層 isScale:false,//比例彈出層 scaleValue:'',//分成比例 userId:'', isActive:true,//操作協議按鈕灰色顯示 sencond:5,//秒數 btntxt:'', //操作協議層按鈕文字顯示 scaleValue:'',//分成比例 scaleDesc:'',//比例彈窗描述 scaleBtn:'', scaleCount:'50%',//預設分成比例 successInvite: [],//預設未邀請 protocolTitle:'',//協議標題 protocolCon:'' //協議內容 }; }, components:{FastChoice,PopUp,scale, SearchContent}, watch: { keyword () { if (!this.keyword){ return; } } }, mounted() { this.protocolAjax(); }, methods: { //邀請 inviteClick (item) { //點選邀請過的不予操作 if(this.successInvite.indexOf(item.hwUserId) > -1 || item.inviteStatus){ return; } this.isScale = true; this.userId = item.hwUserId; this.scaleDesc = '邀請成功後你可獲取該使用者部分收益,選擇雙方都認可的分成比例可以提高邀請成功率哦~'; this.scaleBtn = '傳送邀請'; this.scaleCount = '50%';//邀請比例統一為50% }, //點擊發送邀請 sendAjaxClick (value){ this.scaleValue = value; this.popuShow = true; this.isScale = false; this.isActive = true; this.sencond = 5 ; this.timer(); }, //5s時間倒計時 timer() { if (this.sencond > 0) { this.btntxt="已閱讀同意並確認邀請("+this.sencond+"s)"; this.sencond--; t=setTimeout(this.timer, 1000); } else{ this.isActive = false; this.sencond = 5; this.btntxt="已閱讀同意並確認邀請"; } }, //已閱讀同意並確認 confirmProtocol () { if(this.isActive){ return false; } this.sendAjax(); }, //傳送邀請請求 sendAjax () { console.log(this.scaleValue); let dd = this.scaleValue.toString(); this.$request.post(_basePath + '/activity/page20191018/inviteArtist.html
',{userId: this.userId,shareRate:this.scaleValue}).then((res) => { this.successInvite.push(this.userId) ; mui.toast("已傳送邀請,對方接受後會通知你哦",2000); this.closeActionClick(); }).catch(() => {}) }, //關閉操作協議彈窗 closeActionClick() { this.popuShow = false; clearTimeout(t);//清除倒計時 }, //關閉分成比例彈窗 closeScale () { this.isScale = false; }, clear () { this.keyword = ""; this.$refs["input"].focus(); }, protocolAjax () { this.$request.post(_basePath + '/activity/page20191018/queryProtocol.html',{type:0}).then((res) => { this.protocolTitle = res.title; this.protocolCon = res.content; }).catch(() => {}) } }, }; </script> <style lang="scss" scoped> @import "search"; </style>

子元件處理:

<template>
    <div>
        <div ref="mescroll" class="mescroll">
            <div class="search-content wrapper" ref="scroller" >  
                <ul>
                    <li class="item"  v-for="(item,index) in dataList" :key="index">
                        <div class="personBlock" @click="openUserClick(item.userDetail.userId)">
                            <div class="showImg">
                                <img :src="item.userDetail.userThumUrl" />
                                <template  v-if="item.userDetail.kolFlag">
                                    <em v-if="item.userDetail.kolFlag" class="icon c_kol"></em>
                                </template>
                                <template  v-else>
                                    <em class="icon c_company" v-if="item.userDetail.upSignType == '1'"></em>
                                    <em class="icon c_person" v-if="item.userDetail.upSignType == '0'"></em>
                                </template>
                                
                            </div>
                            <div class="showInfo">
                                <div class="name">{{item.userDetail.nickName}}</div>
                                <div class="attentionCount">
                                    {{item.userDetail.fansCount || 0}}人關注TA
                                </div>
                            </div>
                        </div>
                        <div class="sendBtn" :class="{active:item.userDetail.inviteStatus || (successInvite.indexOf(item.userDetail.hwUserId) > -1 ) }"  @click="inviteClick(item.userDetail)">
                            <span v-if="item.userDetail.inviteStatus || successInvite.indexOf(item.userDetail.hwUserId) > -1">已邀請</span>
                            <span v-else>邀請</span>
                        </div>
                    </li>  
                </ul> 
                
            </div>
        </div>
        <empty v-show="isEmpty">
            <p class="note">納尼,竟然找不到這個人…</p>
        </empty>
    </div>    
</template>

<script>
import MeScroll from 'mescroll.js';
import 'mescroll.js/mescroll.min.css';
import Empty from './empty';
 const pageSize=10;
export default {
    name: 'SearchContent',
    props: {
        searchName: {
            type: String,
            default: ''
        },
        successInvite: {
            type: Array,
            default: []
        }
    },
    data() {
        return {
            dataList: [],
            mescroll: null, //mescroll例項物件
            totalPage:1,
            isEmpty:false
        }
    },
    components:{
       Empty 
    },
    watch: {
        'searchName' () {
            this.dataList = [];//要清空,不然有時候會出現上拉載入不了
            this.searchName !== '' && this.mescroll.resetUpScroll();
        }
    },
    mounted () {
        console.log(this.searchName)
        this.mescroll = new MeScroll(this.$refs.mescroll, { //在mounted初始化mescroll,確保此處配置的ref有值
            down:{isLock: true}, //下拉重新整理的配置. (如果下拉重新整理和上拉載入處理的邏輯是一樣的,則down可不用寫了)                       
            up: {
                    callback: this.upCallback,
                    // 以下是一些常用的配置,當然不寫也可以的.
                    page: {
                        num: 0, //當前頁 預設0,回撥之前會加1; 即callback(page)會從1開始
                        size: 10, //每頁資料條數,預設10
                    },
                    htmlLoading: '<p class="upwarp-progress mescroll-rotate"></p><p class="upwarp-tip">正在載入中..</p>',
                    htmlNodata: '<p class="upwarp-nodata" style="height:.4rem">噹噹噹~已經到底啦~</p>',
                    noMoreSize: 1, //如果列表已無資料,可設定列表的總數量要大於5才顯示無更多資料;
                    isBounce: true,
            },
            down:{
                use:false
            },
        });
    },
    methods: {
         //點選調起個人主頁
        openUserClick (item) {
            console.log(item)
            var userId = item;
             mui.openClient({"pageType": "userHome","userId":item});
        },
         //上拉回調 page = {num:1, size:10}; num:當前頁 ,預設從1開始; size:每頁資料條數,預設10
        upCallback(page) {
            //聯網請求
            this.$request.post(_basePath + '/activity/page20191018/searchAll.html', {hintKey:this.searchName,searchType:91,pageNo:page.num,pageSize:page.size,actionSource:'07'}).then((response) => {
                    if(response && response.resultList){
                      // 請求的列表資料
                        let result = response.resultList[0];
                        let arr = result.list;
                        // 如果是第一頁需手動置空列表
                        if (page.num === 1) this.dataList = []
                        // 把請求到的資料新增到列表
                        this.dataList = this.dataList.concat(arr)
                        // 資料渲染成功後,隱藏下拉重新整理的狀態
                        this.totalPage = result.total % pageSize > 0 ? Math.floor(result.total / 10 + 1) : result.total / 10;//計算總頁數超過就不loadMore
                        this.$nextTick(() => {
                                this.mescroll.endSuccess(arr.length);
                                this.mescroll.endByPage(arr.length, this.totalPage)
                        }) 
                    }else{
                        this.isEmpty = true;
                        this.mescroll.endErr();
                    }                    
            }).catch(() => {
                    this.mescroll.endErr();
            })
        },
        inviteClick(item) {
            this.$emit('inviteClick',item);
        }
}

}
</script>

<style lang="scss" scoped>
.mescroll {
    position: fixed;
    top: .9rem;
    bottom: 0;
    left:0;
    height: auto;
}
.search-content{
    padding:0 .24rem; 
    background: #121223;
    ul{
        height:auto;
        .item{
            display:flex;
            justify-content:space-between;
            align-items:center;
            width:100%;
            height:1.56rem;
            .personBlock{
                display:flex;
                justify-content: flex-start;
                align-items: center;
                .showImg{
                    position:relative;
                    width:1rem;
                    height:1rem;
                    margin-right:.16rem;
                    border:.02rem solid #51516D;
                    border-radius:50%;
                    box-sizing: border-box;
                    img{width:100%;height:100%;border-radius:50%}
                    .icon{
                        position: absolute;
                        bottom:0;
                        right:0;
                        width:.28rem;
                        height:.28rem;
                        background-image:url();
                        background-repeat:no-repeat;
                        background-size:contain;
                        &.c_company{background-image:url(../../images/c_company.png);}
                        &.c_person{background-image:url(../../images/c_person.png);}
                        &.c_kol{background-image:url(../../images/kol.png);}
                    }
                }
                .showInfo{
                    .name{font-size:.3rem;color:#fff;font-weight:500;line-height:.42rem;text-align:left;}
                    .attentionCount{font-size:.26rem;font-weight:400;color:#716D80;text-align:left;}
                }
            }
            
            .sendBtn{
                width:1.44rem;
                height:.56rem;
                line-height:.56rem;
                background:#FF005E;
                border-radius:.28rem;
                color:#fff;
                text-align:center;
                &.active{background:#2C2B41;color:#fff}
            }
        }
    }
}    

</style>

資源搜尋網站大全 http://www.szhdn.com

填坑處理:

1、使用者未輸入搜尋關鍵詞時,mescroll不能就直接初始話,要在使用者輸入的時候才能初始化,所以子元件就接受了父元件的keyword,並用 v-if="keyword !== ''"來判斷載入子元件的條件,然後子元件通過監聽keyword的變化,重置mescroll:如下:

watch: {
        'searchName' () {
            this.dataList = [];//要清空,不然有時候會出現上拉載入不了
            this.searchName !== '' && this.mescroll.resetUpScroll();
        }
    },

2、搜尋完以後點選搜尋輸入框右邊裡的關閉按鈕,發現其他列表不能滑動。解決方法:要加:isBounce: true