2

I'm using Element UI component in Vue.js and would like to add scroll management function to implement infinite scroll.

[This is a code of screenshot: Please take a look Example section] http://element.eleme.io/#/en-US/component/container

I tried the following code but infiniteScroll method was not called even if I scroll this section.

<el-main @scroll="infiniteScroll">......</el-main>

Also, I tried below as well, but it was not working because this page has two scrolls (in nav/content) and want to call infiniteScroll method when content is scrolled only.

created: function () {
  window.addEventListener('scroll', this.infiniteScroll);
},
destroyed: function () {
  window.removeEventListener('scroll', this.infiniteScroll);
}

Do you guys have the best solution?

enter image description here

4
  • Your Jsfiddle link is broken Commented Aug 28, 2018 at 8:10
  • @Muhammad Osama -Thank you for letting me know. I have changed the URL. Commented Aug 28, 2018 at 8:16
  • You have the right idea in your second attempt. but you are binding the event listener to the wrong element. Add a ref attribute to your main el-main element, find the content and bind the scroll event listener to that element instead Commented Aug 28, 2018 at 8:31
  • @Chinonso Chukwuogor Thank you for your comment. I tried your solution but had the following error: "TypeError: this.$refs.myInfiniteScroll.addEventListener is not a function" I changed it to id from ref as Nomis's suggest, then it worked. Commented Aug 28, 2018 at 8:56

2 Answers 2

12

<el-main @scroll="infiniteScroll">......</el-main> doesn't work because when binding an event on a component, Vue listens for custom events by default.

If you want to listen for a native event you have to use the .native modifier:

<el-main @scroll.native="infiniteScroll">......</el-main>

Check demo

Sign up to request clarification or add additional context in comments.

1 Comment

-Thank you very much. your answer is the simplest one! This is really good to know!
1

As stated by Chinonso Chukwuogor in the comments, you should attach the listener to the scrolling element you want. Something like that should work :

<el-main id="myInfiniteScroll">......</el-main>

document.getElementById('myInfiniteScroll').addEventListener('scroll', this.infiniteScroll);

If it doesn't, it's more a matter of what is the infiniteScroll method.

1 Comment

Thank you very much. I tried to use ref but had a following error "TypeError: this.$refs.myInfiniteScroll.addEventListener is not a function" I changed it to id that you suggested to me, then it 's working! Thank you again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.