Vue.js 如何将组件中的值绑定到App.vue中的元素?
我想从每个页面组件中的属性或值将类绑定到App.vue中的元素。有点像传递道具的反面?不完全是chld->parent,绝对不是parent->child。我正在尝试使用route参数,但到目前为止,我只能通过刷新获得要绑定到的值。是否有此方法的修复方法或更好的vue方法 App.vue:Vue.js 如何将组件中的值绑定到App.vue中的元素?,vue.js,Vue.js,我想从每个页面组件中的属性或值将类绑定到App.vue中的元素。有点像传递道具的反面?不完全是chld->parent,绝对不是parent->child。我正在尝试使用route参数,但到目前为止,我只能通过刷新获得要绑定到的值。是否有此方法的修复方法或更好的vue方法 App.vue: <template> <div id="app"> <app-header /> <main> ... <!--
<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>
使用该属性的计算属性
computed: {
mainClass: function() {
return this.$route.name.toLowerCase();
}
}
您可以在主App.vue中使用观察者。 假设您的css类具有与路由相同的名称,则返回一个未计算的mainClass数据,因为它不是setter并监视路由。名称:
<template>
<div id="app">
<main :class="mainClass">
...
</main>
</div>
</template>
<script>
data() {
return {
mainClass: ""
}
},
watch: {
'$route.name': function(name) {
this.mainClass = name
}
}
</script>
谢谢你的建议。请看我对phoet的解决方案的评论,我为什么喜欢它作为我的目标。非常感谢。当我对您和sovalina的解决方案有了一些了解后,我意识到我遇到了一个新问题:如何在域中设置mainClass。我无法使用watcher解决这个问题,但我确实成功地使用了computed方法:computed:{mainClass:function{let name=this.$route.name;name=name==Index?Gallery:name;return name.toLowerCase;}