简体   繁体   English

NuxtJS中使用nuxt-link或router-link时如何初始化html元素的属性?

[英]How to initialize the attribute of html elements when using nuxt-link or router-link in NuxtJS?

I have two pages index and blog and I want to manipulate the attribute of html before the rendering of each page, such as setting <html> to <html class="dark"> , so I implement a method initDOM() and call it inside the vue mounted hook function. When I use <a></a> to navigate pages, everything works well.我有两个页面indexblog ,我想在每个页面渲染之前操作html的属性,比如将<html>设置为<html class="dark"> ,所以我实现了一个方法initDOM()并调用它在 vue mounted钩子 function 内。当我使用<a></a>导航页面时,一切正常。 The function is: function 是:

initDOM() {
  let htmlObj = document.getElementsByTagName("html");
  htmlObj[0].setAttribute('class', 'dark')
}

However, when I use <nuxt-link></nuxt-link> to navigate pages, the DOM tree is not initialized by my initDOM() function. I found that it seems because when I use <a></a> , the whole DOM tree is refreshed when going into a new webpage, but the DOM tree is not refreshed when using <nuxt-link></nuxt-link> .但是,当我使用<nuxt-link></nuxt-link>导航页面时,DOM 树没有被我的initDOM() function 初始化。我发现这似乎是因为当我使用<a></a>时,进入新网页时会刷新整个 DOM 树,但在使用<nuxt-link></nuxt-link>时不会刷新 DOM 树。 Although replacing <nuxt-link> by <a> works well, the loading time is obviously longer than using <nuxt-link>虽然将<nuxt-link>替换为<a>效果很好,但加载时间显然比使用<nuxt-link>

Any idea to solve this problem?有解决这个问题的想法吗?

OP solved the issue by using Pinia, so that it could have a successfully working dark mode. OP 通过使用 Pinia 解决了这个问题,因此它可以成功运行黑暗模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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