使用el-menu和vue-router实现页面切换

看一下文件目录结构

Home.vue、Rank.vue、Userceter.vue是3个要跳转的页面,这里只是简单的表示一下,所以这三个文件里没有写太多东西,给大家看一个,其他两个是差不多的

Home.vue:

<template>
  <div>
    首页
  </div>
</template>
<script>
export default {
  name: 'Home'
}
</script>

<style lang="less" scoped>
</style>

这3个页面写好了就定义路由文件,引入各个页面,设置跳转路径:

router.js:

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue' // 首页
import Rank from './views/Rank' // 排行榜
import UserCenter from './views/UserCenter' // 个人中心

Vue.use(Router)

export default new Router({
  mode: 'history', // 去掉url中的#
  routes: [
    {
      path: '/home',
      name: 'home',
      component: Home
    },
    {
      path: '/rank',
      name: 'rank',
      component: Rank
    },
    {
      path: '/userCenter',
      name: 'userCenter',
      component: UserCenter
    }
  ]
})

然后写跳转按钮的界面Tab.vue,使用ElementUI的el-menu,这里要注意的是,要在el-menu里加上router属性,然后el-menu-item的index属性对应的是跳转路径

Tab.vue的内容如下:

<template>
  <div>
    <el-menu :default-active="activeIndex"
      class="el-menu-demo"
      mode="horizontal"
      router
      @select="handleSelect">
      <el-menu-item index="/home">
        首页
      </el-menu-item>
      <el-menu-item index="/rank">
        排行榜
      </el-menu-item>
      <el-menu-item index="/userCenter">
        个人中心
      </el-menu-item>
    </el-menu>
  </div>
</template>
<script>
export default {
  name: 'Tab',
  data() {
    return {
      activeIndex: '/home'
    }
  },
  methods: {
    handleSelect(key, keyPath) {
      console.log(key, keyPath)
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  height: 56px;
}
a {
  text-decoration: none;
}
.router-link-active {
  text-decoration: none;
}
</style>

然后在App.vue中把Tab.vue组件加进来:

<template>
  <div id="app">
    <tab></tab>
    <!-- 存放跳转后的页面 -->
    <router-view></router-view> 
  </div>
</template>
<script>
import Tab from './views/Tab' // 引入tab组件
export default {
  components: {
    Tab
  }
}
</script>

<style lang="less">
* {
  margin: 0;
  padding: 0;
}
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
</style>

 这样就大功告成了。

看下效果:

猜你喜欢

转载自www.cnblogs.com/shmily1213/p/10885322.html