Answer the question
In order to leave comments, you need to log in
Where to write "regular" scripts in Vue js?
Good evening. I am learning Vue js, and I had this question: where to write standard, familiar scripts, for example, smooth scrolling ... I thought that I should use hooks, but a problem arose:
I have such a simple code, and it works, but if I switch to another route, and then return to the same one, an error is written in the console: "Uncaught TypeError: Cannot read property 'style' of undefined"
PS while the script continues to work
created () {
window.addEventListener('scroll', () => {
let el = this.$refs.parallax;
let val = document.documentElement.scrollTop / 100;
el.style.filter = `blur(${val}px)`;
})
}
Answer the question
In order to leave comments, you need to log in
I would advise you to learn some hooks and what happens in your case. You are initializing the scroll in the created hand, but on this hook, the component is not yet in the tree home, so you are catching an error. You need to use the same code in the mounted hook.
I found something, maybe it will help someone:
methods: {
blur () {
let el = this.$refs.parallax;
let val = document.documentElement.scrollTop / 100;
el.style.filter = `blur(${val}px)`;
}
},
created () {
window.addEventListener('scroll', this.blur)
},
destroyed () {
window.removeEventListener('scroll', this.blur);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question