1.安装vue-router, 一般在项目构建的时候,会提示是否需要安装vue-router,点击y就可以,默认选择也是安装的,如果没有安装,使用命令去安装,查看是否安装,可以输入命令npm vue-router -v,安装了cnpm的,也必须要使用npm来查看,否则找不到。还有一种,在package.json中查看是否存在vue-router
"dependencies": { "less": "^2.7.2", "less-loader": "^4.0.5", "vue": "^2.4.2", "vue-router": "^2.7.0" },
2.安装好了以后,需要引入:
在main.js中引入vue-router,如果在构建项目的时候,提示了是否安装vue-router并点击y的情况下,项目自动会在main.js中引入,无需再次引入,
如果自己重新安装的,则需要在main.js中引入它。(以下代码是构建项目时自动引入的)
import Vue from 'vue' import App from './App'
3.我的的src-router-index.js如下
import Vue from 'vue' import Router from 'vue-router' import goods from '../pages/Goods/Goods' import ratings from '../pages/Ratings/Ratings' import seller from '../pages/Seller/Seller' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'goods', component: goods }, { path: '/ratings', name: 'ratings', component: ratings }, { path: '/seller', name: 'seller', component: seller }, { path: '/goods', redirect: '/' }, { path: '*', redirect: '/' } ] })
4.App.vue中的代码如下
<template> <div id="app"> <m-header></m-header> <div class="tab"> <div class="tab-item" :class="{active: isActive == item.name}" v-for="item in tab" @click="goToRouter(item)"> {{ item.name }} </div> </div> <router-view></router-view> </div> </template> <script> import mHeader from './components/header/header' export default{ data () { return { isActive: '商品', tab : [ { name: '商品', router: '/', Active: true }, { name: '评论', router: '/ratings', Active: false }, { name: '商家', router: '/seller', Active: false } ] } }, created: { }, methods: { goToRouter (item) { //初始化data中的isActive,当点击某一个item的时候,:class中isActive == item.name的值为true this.isActive = item.name this.$router.push(item.router) // console.log(item.Active,this.isActive) } }, components: { mHeader } } </script> <style lang="less"> #app{ .tab{ display: flex; width:100%; height:80px; line-height: 80px; .tab-item{ flex-grow:1; text-align: center; font-size:28px; color: #4d555d; line-height:28px; border-bottom:2px solid rgba(7,17,27,0.1) } .active{ color: #f01414; } } } </style>