如何使用 vue 保持 css 样式

how to keep css style by using vue

我正在学习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(选项卡class为nav-li active)和浏览器url 是 /execution/list。但是,我刷新页面后,management标签的class是nav-li active,背景颜色是#FFCC00,而url仍然是/execution/list。为什么management标签的class变成了nav-li activeexecution标签的class变成了nav-li

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

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