Michael Cole
Michael Cole

Reputation: 16217

Nuxt.js run code on page load

How do I run code when a page loads with Nuxt.js?

I'd like to add a class if the browser supports touch events using !!window.ontouchstart.

I tried this, but window is undefined:

```
<section v-bind:class="{ touch: !!window.ontouchstart }">
   ...
</section>
```

Upvotes: 2

Views: 15633

Answers (1)

Helping hand
Helping hand

Reputation: 2920

You need to first add an eventlistener to listen to touchstart.

created: function(){
    document.addEventListener('touchstart',this.touchStart);
 }, 
destroyed: function() { 
    document.removeEventListener('touchstart', this.touchStart); 
 }

Now you can use touch touchStart method inside Vue methods.

methods:{
  touchStart(e){
    this.touched=true;
  }

}

In html

<section v-bind:class="{ touch: touched}"> ... </section>

Also ontouchstart is a window event which is not yet standardized, So replace document with window.

Upvotes: 1

Related Questions