简体   繁体   中英

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. The function is:

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> . Although replacing <nuxt-link> by <a> works well, the loading time is obviously longer than using <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.

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