vue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,适合用于构建单页面应用。vue的单页面应用是基于路由和组件的,路由用于设定访问路径,并将路径和组件映射起来。传统的页面应用,是用一些超链接来实现页面切换和跳转的。在vue-router单页面应用中,则是路径之间的切换,也就是组件的切换。
注意:vue-router 2只适用于Vue2.x版本,下面我们是基于vue2.0讲的如何使用vue-router 2实现路由功能。
推荐使用npm安装。
npm install vue-router
一、使用路由
在main.js中,需要明确安装路由功能:
import Vue from 'vue' import VueRouter from 'vue-router' import App from './App.vue' Vue.use(VueRouter)
1.定义组件,这里使用从其他文件import进来
import index from './components/index.vue' import hello from './components/hello.vue'
2.定义路由
const routes = [
{ path: '/index', component: index },
{ path: '/hello', component: hello },
]
3.创建 router 实例,然后传 routes 配置
const router = new VueRouter({
routes
})
4.创建和挂载根实例。通过 router 配置参数注入路由,从而让整个应用都有路由功能
const app = new Vue({
router,
render: h => h(App)
}).$mount('#app')
经过上面的配置之后呢,路由匹配到的组件将会渲染到App.vue里的<router-view></router-view>
那么这个App.vue里应该这样写:
<template> <div id="app"> <router-view></router-view> </div> </template>
index.html里呢要这样写:
<body> <div id="app"></div> </body>
这样就会把渲染出来的页面挂载到这个id为app的div里了。
二、重定向 redirect
const routes = [
{ path: '/', redirect: '/index'}, // 这样进/ 就会跳转到/index
{ path: '/index', component: index }
]
三、嵌套路由
const routes = [
{ path: '/index', component: index,
children: [
{ path: 'info', component: info}
]
}
]
通过/index/info就可以访问到info组件了
四、懒加载
内容版权声明:除非注明,否则皆为本站原创文章。
