Guide to programmatically configuring meta title, description, and image in a Vue.js project with the help of Vue Unhead and Vue Meta

I'm currently developing a Vue.js project where I need to dynamically set the meta title, description, and image based on data fetched from an API. To handle the meta tags, I am utilizing Vue Vue Unhead along with Vue Meta. Below is a snippet of the relevant code in my project:

Inside main.js:

import "./assets/main.css";

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import "./plugins";
// import { createMetaManager } from "vue-meta";
import { createHead } from '@unhead/vue'

const app = createApp(App);
app.use(router);
app.use(store);
// app.use(createMetaManager()); // Use Vue Meta plugin
const head = createHead()
app.use(head)
app.mount("#app");

On the detail page's onMounted function, I initiate a call to an API function using axios to retrieve the necessary data.

import { onMounted } from "vue";
import axios from "axios";

onMounted(() => {
  fetchOperatorDetail();
});

function fetchOperatorDetail() {
  axios.get(
    `api/route`,
    {
      headers: {
        'time_zone': timeZone,
      }
    }
  ).then((response) => {
    if (Object.keys(response.data.data).length > 0) {
      // Extracting data from the API response
      // How can I dynamically set this extracted data as the meta title, description, and image?
    }
  });
}

The core objective is for the meta title, description, and image to be displayed when sharing the URL of the detail page across different platforms.

While I have managed to set static text for the meta title, I'm encountering difficulties in dynamically updating the description and image based on the API response. I would appreciate any guidance on achieving this using Vue Unhead and Vue Meta or any alternative approaches.

Additional information:

  1. I have already attempted to use Vue Unhead and Vue Meta for managing the meta tags.
  2. The project is developed with Vue.js version 3.

UPDATE Here is how my Index.js file looks:

import { createRouter, createWebHistory } from "vue-router";
import ListView from "../components/views/ListView.vue";
import { nextTick } from "vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      component: ListView,
     // meta: { title: "ListView" },
    },
    {
      path: "/:detailpage/:packageid?",
      name: "detailpage",
      component: () => import("../components/views/detail page.vue"),
      //meta: { title: "detail page" },
    },
  ],
});

// const DEFAULT_TITLE = "detailpage";

// router.afterEach((to, from) => {
//   nextTick(() => {
//     document.title = to.meta.title || DEFAULT_TITLE;
//   });
// });

export default router;

Answer №1

Learn how to utilize useHead in Vue Unhead

import { onMounted } from "vue";
import axios from "axios";
import { useHead } from '@unhead/vue'

const title = ref('')
useHead({
  title,
})

onMounted(() => {
  fetchData();
});

function fetchData() {
  axios.get(
    `api/route`,
    {
      headers: {
        'time_zone': timeZone,
      }
    }
  ).then((response) => {
    if (Object.keys(response.data.data).length > 0) {
      // Extract important data from the API response
      title.value = response.data.data.title || ''
    }
  });
}

For more information, refer to the official documentation

Answer №2

Reactive title and meta description can be achieved by utilizing functions instead of hardcoded values.

import { useHead } from '@unhead/vue';

const dynamicTitle = ref('');
const dynamicDescription = ref('');

useHead({
  title: () => dynamicTitle.value,
  meta: () => [
    { name: 'description', content: dynamicDescription.value }
  ]
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js now supports ES6 imports using the `--experimental-modules` flag,

Experimenting with ES6 imports in node using the -experimental-modules flag. Here are the steps: mkdir testfolder cd testfolder npm init npm i --save testing-library touch script.mjs Next, add the following code to script.mjs: import { test1, test2, tes ...

How can I add a channel to a category using await(discord.js)?

Having trouble organizing a new channel within a category. The .setParent(categoryID) method seems to only work with existing channels, causing an issue when I attempt to execute my code. Take a look at the code snippet below: client.on("message" ...

The problem with the first item title in the Jquery slider is causing

I've been working on setting up a Jquery slider (caroufredsel) in which I want certain elements to be displayed above the slider itself, outside of the wrapper. Everything is working fine except for the first slide! After spending several days trying ...

What is the best way to vertically align an InputLabel within a MUI Grid item?

I'm trying to vertically center the InputLabel inside a MUI Grid item. Here's what I've attempted: import { FormControl, Grid, Input, InputLabel, TextField } from "@mui/material"; export default function App() ...

Delving into the World of ReactJS Routing Components and Rendering

I recently developed a basic booking app consisting of 3 essential files - App.js, Booked.js (1st child), and Details.js (2nd child). My current dilemma involves attempting to access App.js for the purpose of deleting data using the 2nd child (Detail.js). ...

I can't find my unit test in the Test Explorer

I'm currently working on configuring a unit test in Typescript using tsUnit. To ensure that everything is set up correctly, I've created a simple test. However, whenever I try to run all tests in Test Explorer, no results are displayed! It appear ...

Employ AJAX to dynamically refresh the page whenever a new row is inserted into the table

Currently, I am in the midst of learning AJAX because it is necessary for a project I am working on. The aim is to refresh a feed in real-time whenever a new row is added to a MYSQL table. While I have successfully achieved this using node.js, my client&ap ...

Each time a new client connects, socket.io replicates the information

Exploring Node.js and socket.io for the first time, I have developed a small application where a table is meant to be displayed in real-time via socket.io when a function is triggered through a websocket (function triggers an "emit"). However, I'm fac ...

Guide on troubleshooting Node TypeScript in Visual Studio Code when the JavaScript source is stored in a separate directory

When using Visual Studio Code, I am able to debug and step through the TypeScript source code of Main.ts. This is possible as long as the JavaScript and map files are located in the same folder as the TypeScript source. This setup works well in this struc ...

Developing an npm console application that is "installable" similar to tools like yeoman, gulp, or grunt

Recently dipping my toes into the world of NPM, I've been itching to create a package that functions as a console app (think gulp and grunt). My goal is simple: I want users to be able to run npm install -g mypackage followed by mypackage This sh ...

`Multiple Autocomplete feature that allows rendering of previously selected items`

I've encountered a slight issue with my autocomplete feature. On the same page, I have two different autocompletes set up. Both of them pull elements via ajax from separate sources and use the _render option to display the items. The problem arises wi ...

Sort the elements within the *ngFor loop according to the category upon clicking the button in Angular

Currently, I have a collection of items that I am iterating through using *ngFor. Above this list, there are category buttons available as shown in the HTML snippet below. My goal is to enable filtering of the list based on the category of the button click ...

What is the best way to update the state of a particular slider component?

When trying to update the value of a specific slider during the onChange event, I noticed that it was affecting all sliders instead. Is there a way to target and set the state of only one slider during this event? Here's what I've attempted so f ...

Combining Vue 2 with Bootstrap-vue to create interactive and dynamic attributes

Hello everyone, I'm excited to be taking my first steps in Vue 2 alongside bootstrap-vue. Currently, I am trying to dynamically change the name of an attribute in order to adjust the tooltip position for smaller screen resolutions. The JS code below ...

When using the Infinite Scroll React component, only a single new set of objects is loaded as you scroll down, and the loading

My React component is designed to load 6 images at a time as the page is scrolled down, creating an infinite scroll effect similar to what YouTube and Reddit now use. Currently, when the page loads, it shows the initial 6 images correctly. However, as I c ...

Tips for managing the response from a POST request using jQuery

I'm currently working on sending data via POST to my ASP.Net MVC Web API controller and retrieving it in the response. Below is the script I have for the post: $('#recordUser').click(function () { $.ajax({ type: 'POST', ...

Images failing to load in jQuery Colorbox plugin

I am having an issue with the Color Box jQuery plugin. You can find more information about the plugin here: Here is the HTML code I am using: <center> <div class='images'> <a class="group1" href="http://placehold.it/ ...

"Learn the trick to concealing a modal and unveiling a different one with the power of jquery

Whenever I try to open a modal, then click on a div within the modal in order to close it and open another one, I encounter an issue. The problem is that upon closing the first modal and attempting to display the second one, only the background of the seco ...

What is the process for showcasing a local notification within my application?

Here is the code snippet I am working with: import { LocalNotifications } from '@ionic-native/local-notifications'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scs ...

Remove any URLs and replace them with a text corresponding to the ID of the selected link

I need assistance with a JavaScript code. I have three links, each with a different ID. What I am trying to achieve is that when I click on one of these links, the script should grab the ID, delete all three links, and replace them with text in their place ...