gpt4 book ai didi

javascript - 如何使用vue保持css样式

转载 作者:太空宇宙 更新时间:2023-11-04 06:36:16 25 4
gpt4 key购买 nike

我正在学习 vue 并尝试使用 vue 构建一个网站。并且我在导航栏中设置了两个导航标签。

这是路由器配置文件:

import Vue from 'vue'
import Router from 'vue-router'
import Management from '@/components/Management'
import Execution from '@/components/Execution'

Vue.use(Router)

const router = new Router({
routes: [
{
path: '/',
redirect: { name: 'Management'}
},
{
path: '/management/list',
name: 'Management',
component: Management,
},
{
path: '/execution/list',
name: 'Execution',
component: Execution
}
]
})

router.beforeEach((to, from, next) => {
next();
})

export default router

和 App.vue:

<template>
<div class="container">
<div id="header">
<ul class="nav-ul">
<router-link tag="li" :class="['nav-li', {active: show === 'management'}]" v-on:click="changeShow('management')" :to="{name: 'Management'}"><span>case management</span></router-link>
<router-link tag="li" :class="['nav-li', {active: show === 'execution'}]" v-on:click="changeShow('execution')" :to="{name: 'Execution'}"><span>case execution</span></router-link>
</ul>
</div>
<router-view></router-view>
</div>
</template>

<script>
export default {
data: function(){
return {
show: 'management'
}
},
computed: {
changeShow: function (show) {
this.show = show;
}
},
watch: {
'$route'(to, from) {
if (to.name) {
this.show = to.name.toLowerCase()
}
}
}
}
</script>

<style>
.container {
height: 100%;
}
#header {
height: 50px;
width: 100%;
background-image: linear-gradient(to bottom,#FF3300 0,#ff6600 20%);
}
.nav-ul,.nav-li
{
margin: 0px;
padding: 0px;
list-style: none;
}
.nav-ul
{
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.nav-li {
width: 100px;
height: 38px;
text-align: center;
padding-top: 12px;
font-size: 16px;
}
.nav-li:hover {
background-color: #FFCC00;
cursor:pointer;
}
.nav-li.active {
background-color: #FFCC00;
}
</style>

当我点击 execution 选项卡时,它的背景颜色应该更改为#FFCC00(选项卡类是 nav-li active)和浏览器 url是/execution/list。但是,在我刷新页面后,management 选项卡的类是 nav-li active 背景颜色是#FFCC00 而 url 仍然是 /execution/list 。为什么management标签的类变成nav-li activeexecution标签的类是nav-li

最佳答案

您正在 $route 上运行一个 watch 属性,当路线发生变化时它可以正常工作。但是当你刷新时,路线不会改变因此下划线 watch 永远不会被触发。创建一个 mounted 函数并在那里检查路由名称并相应地修改您的 show 数据。这样的事情应该有效:

mounted(){
this.show = this.$route.name.toLowerCase();
}

关于javascript - 如何使用vue保持css样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54197376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com