根据 vue 中的路由改变颜色 [英] change color depending on route in vue
问题描述
我需要根据路线或路线的道具更改 css 颜色
例如:如果我进入主页,标题需要为红色,如果我进入关于页面,标题需要为绿色
我已经在我的 router.js 中使用路由道具尝试过这个,但后来我无法在标头组件中访问它们.
route.js
path: '/home',组件:() =>import('layouts/MainTemplate.vue'),孩子们: [{小路: '',name: '家',css: '红色',组件:() =>导入('页面/主页')}]
在我的组件中,我使用以下内容
道具:['css']
并显示路由css
{{ css }}
如何使用路由道具做到这一点,并且如果我访问例如家,我的标头组件可以接收它?
更新,例如我可以传递给以下属性:
navbarCSS: {'/': 家: {图片:网址,风格:#ddd}},
我不确定 css
是 vue-router
中支持的键.
因此,您最好直接在相关的导航栏组件上执行此操作
<div id="应用程序"><div id="nav"><div :style="{ color: navbarColors[$route.path] }>导航栏中的自定义文本</div><router-link to="/">Home</router-link>|<router-link to="/about">关于</router-link>
<路由器视图/>
模板><脚本>导出默认{数据() {返回 {导航栏颜色:{'/': '红色的','/about': '蓝色',},}},}
在这里,div
将在 red
和 blue
之间切换,具体取决于您是在根页面还是关于页面.
这是一个 github 存储库示例:https://github.com/kissu/so-vue-route-color(几乎是默认的 vue2 设置,但在需要时)
I need to change css color depending on the route or a prop for a route
For example: if I go to home page the header needs to be red, If I go to the about page the header needs to be green
Ive tryed this with route props in my router.js but then I cant access them in the header component.
route.js
path: '/home',
component: () => import('layouts/MainTemplate.vue'),
children: [
{
path: '',
name: 'home',
css: 'red',
component: () => import('pages/home')
}
]
In my component I use the following
props: ['css']
and to display the route css
{{ css }}
how can I do that with route props and that my header component can receive it if Im visiting for example home?
update, example can I pass to attributes like:
navbarCSS: {
'/': Home: {
image: url,
style: #ddd
}
},
I'm not sure that css
is a supported key in vue-router
.
Hence, you should probably better do it directly on the concerned navbar component like this
<template>
<div id="app">
<div id="nav">
<div :style="{ color: navbarColors[$route.path] }">Custom text in the navbar</div>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view />
</div>
</template>
<script>
export default {
data() {
return {
navbarColors: {
'/': 'red',
'/about': 'blue',
},
}
},
}
</script>
Here, the div
will toggle between red
and blue
depending if you're on the root or about page.
Here is a github repo example: https://github.com/kissu/so-vue-route-color (pretty much the default vue2 setup but in case it is needed)
这篇关于根据 vue 中的路由改变颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!