[英]Nuxt.js – script using document working in the whole project
對於我的 CSS 框架自定義需求,我正在使用一個腳本來實現 onClick 按鈕“脈沖效果”。 目前,我在以 SSR 模式運行的 Nuxt.js 項目的 default.vue 布局的 mounted() 部分運行它。
這是腳本:
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");
});
}
}
這是一個簡單的腳本並且運行良好,但僅在重新加載時並且僅適用於我頁面 DOM 頂部的某些按鈕。
當我將此腳本復制粘貼到組件的腳本部分時,它在組件中運行良好。 但我不想將它包含到每個組件中。
我應該在我的項目中的什么地方添加它以使其在所有組件中工作? 我試圖將它添加到 nuxt-config 但它沒有用。
請幫忙。
我會創建一個插件來為你做那些你需要的東西 go 到nuxt.config.js
plugins: ['~/plugins/pulse.js']
現在你 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");
});
}
})
之后你的指令是全局的,你可以 go 到你想要的任何按鈕並簡單地添加v-pulse
到它
<button v-pulse>Click me</button>
告訴我它是否有效以及您是否收到任何錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.