vue下拉加载插件 之vue-infinite-loading

来源:互联网 发布:手机淘宝在线客服 编辑:程序博客网 时间:2024/06/06 00:19
假设你的项目已经可以正常运行
(1) 安装淘宝镜像 npm install -g cnpm --registry=https://registry.npm.taobao.org
    (安装插件有时需要翻墙,为了避免这种情况我直接安装了淘宝镜像 ) 
(2) 安装插件 cnpm install --save vue-infinite-loading
(3) 在需要的页面中引入vue-infinite-loading :
    <template>
      <div class="container" >
        <div class="firstMs" v-for="item in this.getMoreExpertList">
          <router-link :to="{path: '/teacher',query:{user_id:item.user_id}}">
            <img :src="item.expert_bg" class="big_img">
          </router-link>
          <div class="msContent">
             <router-link :to="{path: '/teacher',query:{user_id:item.user_id}}">
              <span>{{item.name}}</span>
              <span>{{item.title_text}}</span>
             </router-link>
          </div>
          <div class="msNum">
            <img src="/static/img/icon4.png">
            <span>{{item.watch_num}}</span>
          </div>
        </div>
        <infinite-loading :on-infinite="onInfinite" ref="infiniteLoading"></infinite-loading>
        <!-- 放在循环体下,当到此位置时会执行onInfinite方法 -->
    </div>
    </template>
    <script type="text/ecmascript-6">
    import InfiniteLoading from 'vue-infinite-loading';
    import axios from 'axios';
    const api = 'http://hn.algolia.com/api/v1/search_by_date';
    export default {
      data() {
        return {
          getMoreExpertList:[],  //用来存放数据的数组
          page_no:1,   //默认显示第一页数据
          page_size:7,//每次请求7条
        }
      },
      components: {
        InfiniteLoading
      },
      methods: {
        getCourseList(){
          axios.get(api, {
            params: {
              page_no:this.page_no,
              page_size:this.page_size
            }
          }).then((res) => {
           if (res.code == 0) {
              // 如果查询结果为真
              if (res.data.expert_lists.experts.length) {
                // 如果有数据则进入将新的数据与老的数据拼接
                this.getMoreExpertList = this.getMoreExpertList.concat(res.data.expert_lists.experts);
                this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
                this.page_no+=1;  //将页码加1
              }else{
                this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete'); //没有数据显示没有更多
              }
            }
          }).catch((err) => {
              console.log(err)
          })
        },
        onInfinite() {
          if(this.page_no!=1){  //是因为我在页面初始化时请求了第一页的数据,所以当页面等于2时才请求数据
            this.getCourseList()
          }
        },
          
      },
      created() {
        this.getMoreExpertList.length = 0;
        this.getCourseList();
      }
    }
</script>