PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] How to use a querySelector in Nuxt 3?

 October 15, 2022     dom, javascript, nuxt.js, nuxtjs3, vue.js     No comments   

Issue

I'm trying to initialise IntersectionObserver in each page of my website built with Nuxt3.

Therefore, I want to access each HTML element that has a specific CSS class. However, on page change, I noticed that via onMounted hook the detected elements are from the previous page.

Here a easy to reproduce example:

app.vue

<template>
  <div>
    <NuxtPage />
  </div>
</template>

pages/index.vue

<script setup lang="ts">
onMounted(() => {
  console.group("index.vue");
  console.log(document.querySelector("#container"));
  console.groupEnd();
});
</script>

<template>
  <div id="container">
    <h1>INDEX</h1>
    <NuxtLink to="/work">
      Go to work
    </NuxtLink>
  </div>
</template>

pages/work.vue

<script setup lang="ts">
onMounted(() => {
  console.group("work.vue");
  console.log(document.querySelector("#container"));
  console.groupEnd();
});
</script>

<template>
  <div id="container">
    <h1>WORK</h1>
    <NuxtLink to="/">
      Go to index
    </NuxtLink>
  </div>
</template>

Simply, the result in the console always come from the previous DOM. Here the steps:

  • Load the page on index.vue, you see the right element in the console.
  • Go to work.vue using the link.
  • See the console showing the exact same result as previously, yet with an added empty class attribute on #container

My question is, why does onMounted hook doesn't show the right DOM on page change?

I tried to set the page transition to the default mode:

definePageMeta({
  pageTransition: {
    mode: 'default',
  },
});

Nothing changed.

NOTE: I am using nuxt version: 3.0.0-rc.9


Solution

For this kind of usage, you should use template refs: https://vuejs.org/guide/essentials/template-refs.html#accessing-the-refs

Otherwise, Vue will not behave as expected. More details can be found in this other answer.



Answered By - kissu
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing