kicaj
kicaj

Reputation: 2968

Use Nuxt's useHead with visibilitychange event

On every page I set title using useHead({title: ""});.

In layout/default.vue file, I added:

useHead({
  titleTemplate: title => {
    let titleDefault = 'Company suffix';

    if (title) {
      titleDefault = title +  ' - ' + titleDefault;
    }

    return titleDefault;
  }
});

Now every title has suffix added.

But, I tried to change title based on visibilitychange event to to achieve the goal with steps:

  1. Open page "About us", the title should be "About us - Company suffix"
  2. When I switched off tab in browser the title should be changed to "Come back - Company suffix"
  3. But, when I back to tab, title should be changed to previous title, like "About us - Company suffix"

Code below dosen't work, like i suppose:

useHead({
  titleTemplate: title => {
    let titleDefault = 'Company suffix';

    if (title) {
      titleDefault = title +  ' - ' + titleDefault;
    }

    document.addEventListener('visibilitychange', () => {
      if (document.hidden) {
        useHead({
          title: 'Come back',
        });
      } else {
        useHead({
          title: title,
        });
      }
    });

    return titleDefault;
  }
});

Then, steps 1st and 2nd works perfectly, but step 3rd not, nothing do. How to fix it?

Upvotes: 0

Views: 141

Answers (1)

Mike Bellika
Mike Bellika

Reputation: 573

Might be because the title isn't reactive. Try using a computed title instead:

const suffix = "Company suffix";
const pageHidden = ref(false);

const title = computed(() => pageHidden.value ? `Come Back` : `About`)

useHead({title, titleTemplate: (_title) => `${title} - ${suffix}`})
onMounted(() => {
 document.addEventListener('visibilitychange', () => pageHidden.value = document.hidden)
})

I also changed the event handler. Might be good to also remove it on unMounted

Upvotes: 0

Related Questions