FRAMEWORK/VUE

vue infinite loading 활용하기

나나나나나나나ㅏ나난ㄴ나ㅏ나나 2021. 4. 15. 18:05
728x90

vue에서 무한 스크롤 만들어서 사용하기!

 

*공식 문서*

peachscript.github.io/vue-infinite-loading/guide/#installation

 

Guide | Vue-infinite-loading

Guide Installation NPM If you are building a large application, we recommend you use the following method: Direct Include After you import this plugin through the script tag, it will register the InfiniteLoading component automatically, so you can use it i

peachscript.github.io

 

npm install vue-infinite-loading -S
<template>
  <div>
  		<div v-for="(list, listIndex) in list" :key="list.key">
        {{list}} {{listIndex}}
        </div>
  		<infinite-loading v-if="hasMore" :identifier="infiniteId" @infinite="onScroll"></infinite-loading>
  </div>

</template>

<script>
import InfiniteLoading from 'vue-infinite-loading';

export default {
  components: {
    InfiniteLoading,
  },
  data(){
    return{
   		list: [] /* array */,
    	hasMore: this.list.length > 0 ? true : false,
        infiniteId: +new Date(),
        page: this.$route.query.page
    }
  },
  methods: {
  	onScroll($state){
    	if(this.hasMore){
        	const _this = this
            this.page++
            const query = this.$route.query
            
            /* 페이지 하나 더 추가해서 데이터 가져오기 */
            this.$store.dispatch('lists/getList', Object.assign({}, query, {page: this.page})).then(res => {
            	/* 가져온 데이터가 없을경우 스크롤 종료 */
         		if(res.length === 0){
                	$state.complete()
                    _this.hasMore = false
                }else{
                	$state.loaded()
                    _this.hasMore = true
                    /* list에 가져온 데이터 추가하기 */
                    _this.list = [..._this.list || [], ...res]
                }
            }).catch(err => {
            	/* 오류발생시 스크롤 종료 */
                $state.complete
                console.dir('lists/getList err=>')
                console.dir(err)
            })
        }
    }
  }
};
</script>

 

끝!

728x90