Reputation: 243
I would like to bind a class to an element in App.vue, from a property or value in each page component. Kinda the opposite of passing a prop? Not exactly chld -> parent, definitely not parent -> child. I'm trying to use the route param but so far I can only get the value to bind to with a refresh. Is there a fix for this approach or a better, vue way to do this?
App.vue:
<template>
<div id="app">
<app-header />
<main> ... <!-- objective: <main :class="[ get a value from each component loaded into router-view ]"> -->
<router-view />
</main>
</div>
</template>
<script>
export default {
data () {
return {
name: 'App',
mainClass: "", // update this value per route component
}
},
created: function() {
// console.log("this.$routes.params.id", this.$route.params.id); // undefined
this.mainClass = this.$route.name.toLowerCase(); // √
}
}
</script>
gallery.vue:
<script>
import Gallery from '../../data/Gallery.json';
export default {
name: 'Gallery',
data () {
return {
h1: 'Gallery',
Gallery: Gallery,
objID: "",
mainClass: ""
}
},
created: function() {
var Gallery = require('../../data/Gallery.json');
for (let key in Gallery) {
Gallery[key].id = key;
!this.objID ? this.objID = key : ""
}
}, // created
methods: {
setFeaturedImage: function(objID) {
this.objID = objID;
}
}
}
</script>
Upvotes: 0
Views: 194
Reputation: 5609
You can use a watcher in your main App.vue.
Assuming your css classes have the same name of your routes, return a mainClass
data (not computed because it's not a setter) and watch the route.name :
<template>
<div id="app">
<main :class="mainClass">
...
</main>
</div>
</template>
<script>
data() {
return {
mainClass: ""
}
},
watch: {
'$route.name': function(name) {
this.mainClass = name
}
}
</script>
Upvotes: 0
Reputation: 18835
use a computed property for that
computed: {
mainClass: function() {
return this.$route.name.toLowerCase();
}
}
Upvotes: 1