Vue前端路由建立流程

项目默认是vue-cli搭建的。
Vue的前端路由是以模块引入的方式使用的。
node_modules里面会有vue-router这个模块。
开始使用vue-router搭建项目的前端路由。
具体步骤:

  1. 先在入口文件main.js导入,src目录默认有router文件夹,
    import router from “./router”
    然后vue的根组件上注册router
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
  1. 再在网站首页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是插座。插座是用来配套路由标签使用的。

  1. 最后是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>
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值