Is there a way in VueJS to create dynamic backgrounds based on the Route? For instance, I have the followings routes:
const routes = [
{
path: "/",
name: "home",
component: HomeView,
},
{
path: "/:col",
name: "collections",
component: () =>
import(
/* webpackChunkName: "collections" */ "../views/CollectionsView.vue"
),
children: [
{
path: "staked",
name: "staked",
component: () =>
import(/* webpackChunkName: "staked" */ "../views/StakedView.vue"),
},
{
path: "unstaked",
name: "unstaked",
component: () =>
import(
/* webpackChunkName: "unstaked" */ "../views/UnstakedView.vue"
),
},
],
},
];
I would like to set a different background image for each of the dynamic routes under the named route "collections", so "/collection1/..." would display a different background image than "/collection2/.
Here is my template inside AppView.vue:
<template>
<div >
<div
:style="{
backgroundImage: image,
}"
>
<TheAppHeader />
<div >
<TheTitle />
<router-view />
</div>
</div>
</div>
</template>
I don't know how I can grab that collection name from the route and use it to get the desired background image into "".
My background images are all in the /src/assets/ directory.
Any ideas? Thank you!
CodePudding user response:
You can use watch
property for this
watch: {
'$route.params'(currentParam) {
if (currentParam == '/collection1') {
this.image = <put your image here>
}
else if (currentParam == '/collection2') {
this.image = <put your another image here>
}
}
}
Please use to colsole current param to check your required/target values
CodePudding user response:
Can use $route.params
like this.
watch: {
'$route.params'(currentParam) {
this.image = `assets/images/${currentParam}.jpg`
// i.e. assets/images/collection1.jpg
}
}