[英]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".对于我的 CSS 框架自定义需求,我正在使用一个脚本来实现 onClick 按钮“脉冲效果”。 Currently I run it in mounted() part of my default.vue layout in Nuxt.js project running in SSR mode.
目前,我在以 SSR 模式运行的 Nuxt.js 项目的 default.vue 布局的 mounted() 部分运行它。
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.这是一个简单的脚本并且运行良好,但仅在重新加载时并且仅适用于我页面 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.
我试图将它添加到 nuxt-config 但它没有用。
Please help.请帮忙。
I would create a plugin that do that stuff for you you need to go to nuxt.config.js
我会创建一个插件来为你做那些你需要的东西 go 到
nuxt.config.js
plugins: ['~/plugins/pulse.js']
Now you go to your plugins folder and create that pulse.js and write in现在你 go 到你的插件文件夹并创建 pulse.js 并写入
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之后你的指令是全局的,你可以 go 到你想要的任何按钮并简单地添加
v-pulse
到它
<button v-pulse>Click me</button>
Tell me if it works and if you receive any errors.告诉我它是否有效以及您是否收到任何错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.