前言
记录下vue3.0中路由参数的获取
具体实现
route.js
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/detail/:id',
name: 'Detail',
component: Detail
}
]
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('/detail/3')
}
}
}
</script>
home.vue
<template>
<div>首页</div>
<img @click="toDetail" src="@/assets/logo.png" style=" 100%;"/>
</template>
<script>
export default {
name: 'home',
// 定义抛出的事件名称
emits: ['route-change'],
methods: {
toDetail (event) {
// 自定义事件抛出
this.$emit('route-change', event)
}
}
}
</script>
detail.vue
<template>
<div>详情页{{id}}</div>
</template>
<script>
import router from '@/router'
export default {
name: 'detail',
data () {
return {
id: ''
}
},
created () {
console.log(router.currentRoute.value.params)
this.id = router.currentRoute.value.params.id
}
}
</script>