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

How to Animate an Object's Rotation Gently using React Three Fiber App and Use Cannon Library?

I am currently working on a project to create a Tetris-like game using React app, react-three-fiber, and use-cannon. I would like to implement a feature where objects/meshes rotate smoothly when clicked. How can I achieve this? Here is the code for the ob ...

How to mock nested functions within sinon

There are several questions similar to this one, but none of them quite match the scenario I'm dealing with. The situation involves a function that takes another function as a parameter: var myfunc = (func_outer) => { return func_outer().func ...

The AJAX call was successful, however, the response did not contain any data

I have a MySQL table where I use a FOR EACH loop to display data on my page. I then make an AJAX request to update the displayed data every time a new row is inserted into the database. Although the AJAX request is successful, it returns empty data. I&apo ...

What is preventing me from successfully retrieving data at times when using curl_setopt and jQuery Ajax?

In my quest to fetch data from another server, I am using the curl_setopt PHP function along with Ajax. The function I have created seems to be working fine, but sometimes when I refresh the page and the internet connection is slow, I don't receive an ...

Updating $scope from another controller in AngularJS

I am facing an issue where I need to update the $scope inside a directive's link function. Here is what my controller and directive look like: $scope.current = 0; angular.module('myAPP') .directive('post', function() { ...

Tips for removing a DOM element in Selenium using Java

Recently, I've been attempting to remove an element from a website using Selenium and Java with the xpath of the element readily available. WebElement m = driver.findElement (By.xpath ("//*[contains(text(),'discord.gg/')]")); The specific e ...

Encountering a problem with CRUD operations when attempting to edit and save data from a table using

When attempting to edit the information by clicking the radio button, the details are displayed in the appropriate boxes but the existing data in the table is deleted. My goal is to utilize a single array/scope variable for editing, displaying, and deletin ...

What is the best way to restrict datalist options while preserving the "value" functionality?

After finding a creative solution by @Olli on Limit total entries displayed by datalist, I successfully managed to restrict the number of suggestions presented by a datalist. The issue arises from the fact that this solution only covers searching through ...

In order to ensure JavaScript can be universally applied to all images, it needs to be made more generic

I have developed JavaScript functions to enable zoom in and zoom out functionality for an image through pinching gestures. Now, I aim to refactor the code below so that I can include it in a shared JavaScript file. var scale = 1; var newScale; ...

A sleek CSS text link for a stylish video carousel

I am attempting to create a CSS-only text link to video slider within our Umbraco CMS. Due to the limitations of TinyMCE WYSIWYG, I am restricted in the amount of code I can use as it will strip out most of it. So far, I have developed a basic CSS slider ...

What is the best way to add a key to a JavaScript array while keeping it reactive in Vue.js?

If there's an array in the state: state: { users: [] }, Containing objects like: { id: 1, name: "some cool name" } To add them to the store using a mutator like users.push(user);, how can we ensure that instead of 0:{...}, it uses the ...

Laravel triggers a 'required' error message when all fields have been filled

As I attempt to submit a form using an axios post request in laravel, I encounter an issue with the validation of the name and age fields, along with an image file upload. Here is a breakdown of the form structure: Below is the form setup: <form actio ...

Despite the headers being in place, the node is still the point of

I am facing an issue with two URLs residing on the same server, mydomain.com and api.mydomain.com In order to handle access-origin in my API, I have included the following code snippet: app.use(function (req, res, next) { // CORS headers res.head ...

Is it possible to utilize JSX when developing an App using React CDN or the CRA (create-react-app) boilerplate template?

The HTML Code: <div id="app"></div> <script src="https://unpkg.com/react@latest/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@latest/umd/react-dom.develo ...

I'm a beginner when it comes to working with MongoDB and I'm looking to insert a new field into a specific document. Can anyone advise me on how to accomplish this using Node

As an illustration, consider a document structured as follows: {_id:1, name:"John" } If a new field is added, the document will be updated to: {_id:1, name:"John", last_name:"doe" } ...

Retrieving Information from API using Vue.js

In the code snippet below, I am displaying data from an API for all flats on a single page. However, I am facing difficulty in showing the floor number for each flat. The JSON body is as follows: { "response": [ { "fl ...

In JavaScript, where are the values saved?

Can you clarify how JavaScript handles storage for primitive types and objects? Are primitive types always stored on the stack and objects on the heap, even within the scope of a function's execution? Also, are globally scoped variables and functions ...

MUI: Transforming the uncontrolled value state of Select into a controlled one with a new component

I'm attempting to develop an edit form for modifying data fetched from a database based on its ID. Here is what I have tried: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/ ...

What triggers the onmouseout event to occur?

Is the event triggered continuously whenever the mouse is not hovering over the element? Or is it a one-time action when the mouse exits the element? This distinction is crucial for me to determine when the mouse pointer leaves the element, while only wa ...

When the page initially loads, the block appears on top of the upper block and remains in place after the page is refreshed

Upon initial loading, the block appears on top of another block but remains fixed upon page refresh. The same issue occurs in the mobile version of the site and occasionally displays correctly. The website is built on WordPress and optimized using Page Spe ...