简体   繁体   中英

Nuxt.js – script using document working in the whole project

for my CSS framework customization needs I'm using a script for an onClick button "pulse effect". Currently I run it in mounted() part of my default.vue layout in Nuxt.js project running in SSR mode.

This is the script:

if (process.client) {
  var elements = document.querySelectorAll(".button");
  for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener("click", function (event) {
      event.preventDefault;
      this.classList.remove("pulse");
      void this.offsetWidth;
      this.classList.add("pulse");
    });
  }
}

It's an easy script and it's working well but only on reload and only for some buttons which are on the top of my page's DOM.

When I copy-paste this script into a component's script part, it's working in the component well. But I do not want to include it into every component.

Where in my project should I add it to make it working in all components? I've tried to add it into the nuxt-config but it did not work.

Please help.

I would create a plugin that do that stuff for you you need to go to nuxt.config.js

plugins: ['~/plugins/pulse.js']

Now you go to your plugins folder and create that pulse.js and write in

import Vue from 'vue'

Vue.directive('pulse', {
  inserted: (el) => {
    el.addEventListener("click", function (event) {
      event.preventDefault;
      el.classList.remove("pulse");
      void el.offsetWidth;
      el.classList.add("pulse");
    });
  }
})

After that your directive is global and you can go to any button you want and add simply v-pulse to it

<button v-pulse>Click me</button>

Tell me if it works and if you receive any errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM