Vue - route路由跳转
前言
vue
中的route
实现了从一个页面跳转到另一个页面的功能
基本路由跳转
router.js
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/home.vue'
import Detail from '../views/detail'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/detail',
name: 'Detail',
component: Detail
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
router-link 跳转路由
- 实现首页跳转详情页
route-link
相当于a
标签跳转,其指定route-view
显示的内容App.vue
<template>
<div>
<!-- route-view 显示一个route所对应的页面 -->
<router-view/>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
home.vue
<template>
<div>首页</div>
<router-link to="/detail">Detail</router-link>
</template>
<script>
export default {
name: 'home'
}
</script>
detail.vue
<template>
<div>详情</div>
</template>
<script>
export default {
name: 'detail'
}
</script>
router.push(path) 跳转路由
- 通过路由的
path
属性实现首页跳转详情页
App.vue
<template>
<div>
<router-view @route-change="onRouteChange"/>
</div>
</template>
<script>
import router from '@/router'
export default {
name: 'App',
methods: {
/**
* 自定义事件监听
* @param event
*/
onRouteChange (event) {
console.log(event)
router.push('/detail')
}
}
}
</script>
home.vue
<template>
<div>首页</div>
<img @click="toDetail" src="@/assets/logo.png" style="width: 100%;"/>
</template>
<script>
export default {
name: 'home',
// 定义抛出的事件名称
emits: ['route-change'],
methods: {
toDetail (event) {
// 自定义事件抛出
this.$emit('route-change', event)
}
}
}
</script>
router.push(name) 跳转路由
- 通过路由的
name
属性实现首页跳转详情页
App.vue
<template>
<div>
<router-view @route-change="onRouteChange"/>
</div>
</template>
<script>
import router from '@/router'
export default {
name: 'App',
methods: {
/**
* 自定义事件监听
* @param event
*/
onRouteChange (event) {
router.push({
name: event.name
})
}
}
}
</script>
home.vue
<template>
<div>首页</div>
<img @click="toDetail" src="@/assets/logo.png" style="width: 100%;"/>
</template>
<script>
export default {
name: 'home',
// 定义抛出的事件名称
emits: ['route-change'],
methods: {
toDetail (event) {
// 自定义事件抛出
this.$emit('route-change', { name: 'Detail' })
}
}
}
</script>
嵌套路由跳转
- 实现详情页跳转详情子页面
route.js
{
path: '/detail',
name: 'Detail',
component: Detail,
children: [
{
path: '',
name: 'DetailHome',
component: DetailHome
},
{
path: 'sub',
name: 'SubDetail',
component: SubDetail
}
]
}
detail.vue
<template>
<router-view @to-sub-detail="toSubDetail"/>
</template>
<script>
import router from '@/router'
export default {
name: 'detail',
methods: {
/**
* 自定义事件监听
*/
toSubDetail () {
router.push('/detail/sub')
}
}
}
</script>
detail-home.vue
<template>
<div>详情页</div>
<button @click="toSubDetail">跳转子页面</button>
<router-view/>
</template>
<script>
export default {
name: 'DetailHome',
methods: {
toSubDetail () {
// 自定义事件抛出
this.$emit('to-sub-detail')
}
}
}
</script>
sub-detail.vue
<template>
<div>详情子页面</div>
</template>
<script>
export default {
name: 'SubDetail'
}
</script>