在vue ui 里装完vue router插件后,项目自动生成一个router示例
安装
npm install vue-router
yarn add vue-route
使用
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
示例
示例
main.js
import Vue from 'vue'
import App from './App.vue'
import Router from 'vue-router'
import HelloWorld from './components/HelloWorld'
import testRoute from './components/testRoute'
Vue.use(Router)
Vue.config.productionTip = false
const test1 = {
template: '<div>test1</div>'
}
const router = new Router({
// mode: 'history',
routes: [{
path: '/helloWorld',
component: HelloWorld,
},
{
path: '/test1',
component: test1
}, {
path: '/testRoute/:name',
component: testRoute
}
]
})
new Vue({
render: h => h(App),
router,
}).$mount('#app')
app.vue
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<router-view />
<router-link to="/helloWorld">Hello World</router-link>
<br/>
<router-link to="/test1">test1</router-link>
<br/>
<router-link to="/testRoute/name">testRoute</router-link>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'app',
components: {
HelloWorld
}
}
</script>
testRoute.vue 自定义的组件
<template>
<div>
<h1>{{comName}}</h1>
<h1>{{$route.params.name}}</h1>
<h1>{{$route.params}}</h1>
</div>
</template>
<script>
export default {
name: 'testRoute',
data: function() {
return {
name: this.$route.params.name
}
},
computed: {
comName: function() {
return this.$route.params.name
}
}
}
</script>
path 里可以用通配符*
例:
{
// 会匹配所有路径
path: '*'
}
{
// 会匹配以 `/user-` 开头的任意路径
path: '/user-*'
}
当使用一个通配符时,$route.params 内会自动添加一个名为 pathMatch 参数。它包含了 URL 通过通配符被匹配的部分.
可以用正则
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{ path: '/' },
// params are denoted with a colon ":"
{ path: '/params/:foo/:bar' },
// a param can be made optional by adding "?"
{ path: '/optional-params/:foo?' },
// a param can be followed by a regex pattern in parens
// this route will only be matched if :id is all numbers
{ path: '/params-with-regex/:id(\\d+)' },
// asterisk can match anything
{ path: '/asterisk/*' },
// make part of the path optional by wrapping with parens and add "?"
{ path: '/optional-group/(foo/)?bar' }
]
})
•
基础
•
起步
•
动态路由匹配 传递参数,匹配符,正则匹配
•
嵌套路由 子页面
•
编程式的导航 用js跳转页面的方法
•
命名路由 多个路由
•
命名视图 一个页面多个路由显示区域
•
重定向和别名
•
路由组件传参 直接把传的参数弄到组件里
•
HTML5 History 模式 地址栏里不带#,而是传统的地址方式,但是会有小问题
•
进阶
•
导航守卫
•
路由元信息
•
过渡动效
•
数据获取 导航完成前或后获取数据
•
滚动行为 记住滚动的位置
•
路由懒加载 提升首次加载速度
评论区