1、在router/index.js中
- 注册路由插件
Vue.use(VueRouter)
- 定义路由规则
const routers=[
{
path:'/',
name:'Index',
component:Index
},
{
path:'/blog',
name:'Blog',
component:()=>import( '../views/Blog.vue')
},
{
path:'/photo',
name:'Photo',
component:()=>import( '../views/Photo.vue')
}
]
- 创建 router 对象
const router=new VueRouter({
routers
})
- 导出router对象
export default router
在main.js中
- 注册router对象
import router form '/router'
new Vue({
router,
render:h=>h(App)
}).$mount("#app")
在组件中
- 使用路由组件占位
<router-view/>
- 创建链接
<router-link to='/'>Index</router-link>
<router-link to='/blog'>Blog</router-link>
<router-link to='/photo'>Photo</router-link>
动态路由
const routes = [
{
path: '/',
name: 'Index',
component: Index
},
{
path: '/detail/:id',
name: 'Detail',
props: true,
component: () => import( '../views/Detail.vue')
}
]
- 在router/index.js中定义路由规则的时候开启 props,会把 URL 中的参数传递给组件
- 在组件中通过props接收[‘id’]这个参数
嵌套路由
- 加载的时候会先加载Layout,再加载index或detail 组合加载
{
path: '/',
component: Layout,
children: [
{
name: 'index',
path: '',
component: Index
},
{
name: 'detail',
path: 'detail/:id',
props: true,
component: () => import('@/views/Detail.vue')
}
]
}
编程式导航
(1)this.$router.push
- 登录页点击登录按钮跳转到首页 push方法中调用$router.push方法跳转
- $router.push可接收两种参数方式
- 第一种是字符串–跳转的路由地址
- 第二种是传一个对象,传递路由的name ,可以通过params指定路由参数
this.$router.push({ name: ‘Detail’, params: { id: 1 } })
<template>
<div>
用户名:<input type="text" /><br />
密 码:<input type="password" /><br />
<button @click="push"> push </button>
</div>
</template>
<script>
export default {
name: 'Login',
methods: {
push () {
this.$router.push('/')
}
}
}
</script>
<style>
</style>
$router.replace方法
- $router.replace方法不会记录本次历史
<template>
<div class="home">
<div id="nav">
<router-link to="/">Index</router-link>
</div>
<button @click="replace"> replace </button>
<button @click="goDetail"> Detail </button>
</div>
</template>
<script>
export default {
name: 'Index',
methods: {
replace () {
this.$router.replace('/login')
},
goDetail () {
this.$router.push({ name: 'Detail', params: { id: 1 } })
}
}
}
</script>
this.$router.go
可传递数值 如果是 -1 的话 相当于 $router.back
this.$router.go(-2)