美文网首页
vue-router 基础介绍

vue-router 基础介绍

作者: 有你有团 | 来源:发表于2020-03-20 14:19 被阅读0次

Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌

功能

  • 嵌套的路由/视图表
  • 模块化的、基于组件的路由配置
  • 路由参数、查询、通配符
  • 基于 Vue.js 过渡系统的视图过渡效果
  • 细粒度的导航控制
  • 带有自动激活的 CSS class 的链接
  • HTML5 历史模式或 hash 模式,在 IE9 中自动降级
  • 自定义的滚动条行为

安装

使用npm

npm install vue-router

使用 bower

bower install vue-router

使用cdn

<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

起步

用 Vue.js + Vue Router 创建单页应用,是非常简单的。使用 Vue.js ,我们已经可以通过组合组件来组成应用程序,当你要把 Vue Router 添加进来,我们需要做的是,将组件 (components) 映射到路由 (routes),然后告诉 Vue Router 在哪里渲染它们
vue项目中首先在router中新建index.js

//index.js
import Vue from 'vue' //引入vue
import VueRouter from 'vue-router' //引入vue-router
import Login from '@/view/Login.vue'
import NotFoundfrom '@/view/NotFound.vue'
Vue.use( VueRouter )

//配置路由参数
//公共路由-没有权限,token
const commonRoutes = [
  {
    path:'/', 
    name:'',
    component:Login,
    redirect:'/login', //重定向
  }
]
//菜单路由
const menuRoutes = [
  {
    path:'/', 
    name:'',
    component:Login,
    redirect:'/login', //重定向
    children:[    //子路由
       {  
         path: 'population',
         name: 'population',
         component: Population,
         meta: {  //meta参数
          title: '人口'
        } 
      }  
    ]
  }
]
//匹配出错
const wildcardRoutes = [
  {
    path: '*',
    name: 'notfound',
    component: NotFound
  }
]
const constantRoutes = [].concat(commonRoutes,menuRoutes ,wildcardRoutes )
export default new VueRouter ({
  mode:'hash', //默认hash模式,可以改为history模式
  base:'./',  //如果是history模式就可以不用写基础路径了
  routes:constantRoutes 
})

main.js 引入

//main.js
import router from './router'
new Vue({
  router
})

相关文章

网友评论

      本文标题:vue-router 基础介绍

      本文链接:https://www.haomeiwen.com/subject/ftdjyhtx.html