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:
- I have already attempted to use Vue Unhead and Vue Meta for managing the meta tags.
- 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;