项目默认是vue-cli搭建的。
Vue的前端路由是以模块引入的方式使用的。
node_modules里面会有vue-router这个模块。
开始使用vue-router搭建项目的前端路由。
具体步骤:
- 先在入口文件main.js导入,src目录默认有router文件夹,
import router from “./router”
然后vue的根组件上注册router
new Vue({
router,
render: h => h(App)
}).$mount('#app')
- 再在网站首页app.vue里引入已经在src/router/index.js里写好的组件并添加样式。
<template>
<div>
<ul>
<router-link active-class="active" tag="li" to="/movie">电影</router-link>
<router-link active-class="active" tag="li" to="/theater">影院</router-link>
</ul>
<router-view></router-view>
</div>
</template>
<style lang="stylus" scoped>
li.active
font-size 30px
color red
</style>
router-link 标签是路由,router-view是插座。插座是用来配套路由标签使用的。
- 最后是src/router/index.js里的内容。
先引入:
前置依赖是vue模块和vue-router模块,写了哪些组件引入哪些组件。
import Vue from 'vue'
import VueRouter from 'vue-router'
import Movie from '../views/Movie.vue' //一级路由
import Theater from '../views/Theater.vue' //一级路由
import TComp1 from '../views/TCom1.vue' //二级路由
import TComp2 from '../views/TCom2.vue' //二级路由
挂载路由模块 。
Vue.use(VueRouter)
初始化一个VueRouter的对象,并配置路由表。
const routes = [
{
path: '/',
redirect: '/movie'
},
{
path: '/movie',
component: Movie
},
{
path: '/theater',
component: Theater,
redirect: '/theater/tcom1',
children: [
{
path: 'tcom1',
component: TComp1
},
{
path: 'tcom2',
component: TComp2
}
]
}
]
const router = new VueRouter({
mode: 'history',
routes
})
export default router
因为要从Theater扩展二级路由,Theater.vue组件的模板内容如下:
<template>
<div>
<ul>
<router-link to="/theater/tcom1" tag="li">comp1</router-link>
<router-link to="/theater/tcom2" tag="li">comp2</router-link>
</ul>
<router-view></router-view>
</div>
</template>