(Nuxt) Vue component doesn't show up until page refresh

Viewed 1203

I'm storing nav items in my Vuex store and iterating over them for conditional output, in the form of a Vue/Bulma component, as follows:

<b-navbar-item
  v-for='(obj, token) in $store.state.nav'
  v-if='privatePage'
  class=nav-link
  tag=NuxtLink
  :to=token
  :key=token
>
  {{obj.text}}
</b-navbar-item>

As shown, it should be output only if the component's privatePage data item resolves to true, which it does:

export default {
  data: ctx => ({
    privatePage: ctx.$store.state.privateRoutes.includes(ctx.$route.name)
  })
}

The problem I have is when I run the dev server (with ssr: false) the component doesn't show up initially when I navigate to the page via a NuxtLink tag. If I navigate to the page manually, or refresh it, the component shows.

I've seen this before in Nuxt and am not sure what causes it. Does anyone know?

2 Answers

recommendation :

  1. use mapState and other vuex mapping helper to have more readable code :).

  2. dont use v-for and v-if at the same element

  3. use "nuxt-link" for your tag

  4. use / for to (if your addresses dont have trailing slash)

<template v-if='privatePage'>
  <b-navbar-item
    v-for='(obj, token) in nav'
    class=nav-link
    tag="nuxt-link"
    :to="token"  Or "`/${token}`"
    :key="token"
  >
    {{obj.text}}
  </b-navbar-item>
</template>

and in your script :

<script>
import {mapState} from 'vuex'

export default{
   data(){
    return {
      privatePage: false
    }
   },
   computed:{
     ...mapState(['privateRoutes','nav'])
   },
   mounted(){
       // it's better to use name as a query or params to the $route
     this.privatePage = this.privateRoutes.includes(this.$route.name)
   }
}

</script>

and finally if it couldn't have help you , I suggest to inspect your page via dev tools and see what is the rendered component in html. it should be an <a> tag with href property. In addition, I think you can add the link address (that work with refresh and not by nuxt link) to your question, because maybe the created href is not true in navbar-item.

NOTE: token is index of nav array . so your url with be for example yourSite.com/1.so it's what you want?

This question has been answered here: https://stackoverflow.com/a/72500720/12747502

In addition, the solution to my problem was a commented part of my HTML that was outside the wrapper div.

Example:

<template>
  <!-- <div>THIS CREATES THE PROBLEM</div> -->
  <div id='wrapper'> main content here </div>
</template>

Correct way:

<template>
  <div id='wrapper'>
    <!-- <div>THIS CREATES THE PROBLEM</div> -->
    main content here
  </div>
</template>
Related