基于路由动态插入CSS类到导航栏 [英] Dynamically inserting a CSS class to navbar based on route
问题描述
Vue 2 和 Vue-Router 2.
我正在尝试根据访问的路线更改我的应用程序导航栏的颜色.这是我所拥有的:
main.js:
从../components/App.vue"导入应用const app = new Vue({路由器:路由器,模板:'<app></app>',组件:{应用}}).$mount('#app')
App.vue:
<div><div class="navbar" v-on:class="{ colorNav: 'color-nav' }"></div><路由器视图></路由器视图>
</模板><脚本>导出默认{数据() {返回 {颜色导航:假}}}
使用此设置,由于 colorNav
属性为 false,color-nav
类不会添加到导航栏.按预期工作.
现在用户转到 /somepage
,它映射到 SomePage.vue,它在 router-view
中呈现.我希望 SomePage.vue 更改 App.vue 上的 colorNav
属性,以便将 color-nav
类添加到导航栏.
我该怎么做?
有多种方法可以做到.我自己有不同类型的标题,具体取决于我所在的页面.
一种简单的方法是检查您所在的路线,并根据路线更改此变量.您可以在$route
上放置一个手表,当它发生变化时,您可以根据当前路线决定colorNav
的值.代码将类似于:
另一种方法是在一些中心化状态 或 vuex 存储并根据每个组件的挂载块更改它根据要求.
Vue 2 and Vue-Router 2.
I'm trying to change the color of my app's navbar based on which route is visited. Here's what I have:
main.js:
import App from "../components/App.vue"
const app = new Vue({
router: Router,
template: '<app></app>',
components: { App }
}).$mount('#app')
App.vue:
<template>
<div>
<div class="navbar" v-on:class="{ colorNav: 'color-nav' }"></div>
<router-view></router-view>
</div>
</template>
<script>
export default {
data() {
return {
colorNav: false
}
}
}
</script>
With this setting, since colorNav
property is false, the color-nav
class is not added to the navbar. Working as intended.
Now the user goes to /somepage
, which maps to SomePage.vue, which renders inside router-view
. I would like SomePage.vue to change the colorNav
property on App.vue so that color-nav
class is added to the navbar.
How do I do that?
There are multiple ways you can do it. I myself have different kind of headers depending of the page I am on.
One simple way can be to have some check on which route you are and depending on route change this variable. You can put a watch on $route
, and whenever it changes, you can decide the value of colorNav
depending on current route. Code will be something like:
<script>
export default {
data() {
return {
colorNav: false
}
}
watch: {
'$route' () {
if (this.$route.path === '/somepage') {
this. colorNav = true
}
else {
this. colorNav = false
}
}
}
}
</script>
Another way to do it can be have this variable in some centralised state or vuex store and change this from each component's mounted block depending on requirement.
这篇关于基于路由动态插入CSS类到导航栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!