我想从每个页面组件中的属性或值将类绑定到App.vue中的元素。通过道具有点相反?不完全是chld - >父母,绝对不是父母 - >儿童。我正在尝试使用路由参数,但到目前为止,我只能通过刷新获取要绑定的值。是否有针对此方法的修复方法或更好的vue方法来执行此操作?
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>
答案 0 :(得分:1)
为该
使用计算属性 computed: {
mainClass: function() {
return this.$route.name.toLowerCase();
}
}
答案 1 :(得分:0)
您可以在主App.vue中使用观察者
假设您的css类具有相同的路由名称,则返回mainClass
数据(未计算,因为它不是设置者)并观察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>