I solved this thanks to How To Update Page Title and Metadata with Vue.js and vue-router, by Joshua Bemenderfer, which I've borrowed some code from:
create a definitions file definitions.js
export default {
urlTest: "localhost:8080"
}
To keep code logic you need to change the global variables definitions for something like this:
import def from '../definitions.js'
Vue.prototype.$frontUrl = def.urlTest
//Only if you really need to store as a global
then on the vue-router where you define the path:
import HomeView from '../views/HomeView.vue'
import definitions from '../config/definitions.js'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [{
path: '/',
meta: {
title: "Home",
metaTags: [{
//<meta name="image" property="og:image" :content='this.$backUrl + "img/images/portfolio-preview.png"'>
name: 'image',
property: 'og:image',
content: definitions.urlTest + "/img/images/portfolio-preview.png"
}]
},
name: 'home',
component: HomeView
}]
})
// This callback runs before every route change, including on page load.
router.beforeEach((to, from, next) => {
// This goes through the matched routes from last to first, finding the closest route with a title.
// e.g., if we have `/some/deep/nested/route` and `/some`, `/deep`, and `/nested` have titles,
// `/nested`'s will be chosen.
const nearestWithTitle = to.matched.slice().reverse().find(r => r.meta && r.meta.title);
// Find the nearest route element with meta tags.
const nearestWithMeta = to.matched.slice().reverse().find(r => r.meta && r.meta.metaTags);
const previousNearestWithMeta = from.matched.slice().reverse().find(r => r.meta && r.meta.metaTags);
// If a route with a title was found, set the document (page) title to that value.
if (nearestWithTitle) {
document.title = nearestWithTitle.meta.title;
} else if (previousNearestWithMeta) {
document.title = previousNearestWithMeta.meta.title;
}
// Remove any stale meta tags from the document using the key attribute we set below.
Array.from(document.querySelectorAll('[data-vue-router-controlled]')).map(el => el.parentNode.removeChild(el));
// Skip rendering meta tags if there are none.
if (!nearestWithMeta) return next();
// Turn the meta tag definitions into actual elements in the head.
nearestWithMeta.meta.metaTags.map(tagDef => {
const tag = document.createElement('meta');
Object.keys(tagDef).forEach(key => {
tag.setAttribute(key, tagDef[key]);
});
// We use this to track which meta tags we create so we don't interfere with other ones.
tag.setAttribute('data-vue-router-controlled', '');
return tag;
})
// Add the meta tags to the document head.
.forEach(tag => document.head.appendChild(tag));
next();
});
This is with Vue3 but with the method and router path definition has the same format. For a more detailed explanation check the link at the top.