A
A
Andrew2019-11-11 23:10:48
Vue.js
Andrew, 2019-11-11 23:10:48

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

2 answer(s)
A
Andrey Ololoshchenko, 2019-11-12
@veremii

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.

A
Andrew, 2019-11-11
@flokiowl

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);
  }

PS You can't use arrow functions in vue lifecycle hooks

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question