1.路由的路径配置都在index.js文件里,
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
// 两种方式引入页面
const routes = [
{
path: '/',
name: 'Start',
// 方法一
component: () => import('../views/Start.vue')
},
{
path: '/home',
name: 'Home',
// 方法二
component: Home
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
2.页面里进行路由跳转
<template>
<div>
<button @click="start">路由跳转</button>
</div>
</template>
<script>
// 定义一个组件
import {defineComponent} from 'vue'
import {useRouter} from 'vue-router'
export default defineComponent({
name: 'Start',
props:{
},
components:{
},
setup(props,ctx){
//router是全局路由对象,route= userRoute()是当前路由对象
let router = useRouter();
let start = () => {
router.push({
//传递参数使用query的话,指定path或者name都行,但使用params的话,只能使用name指定
path:'/home',
query:{
num:1
}
//name:'Home',
//params:{
//num:1
//}
);
}
return{
start
}
}
})
</script>
<style scoped lang='scss'>
</style>
3.接收参数
<template>
<div>
{{num}}
</div>
</template>
<script>
// 定义一个组件
import {defineComponent} from 'vue'
import {useRoute} from 'vue-router'
export default defineComponent({
name: 'Home',
props:{
},
components:{
},
setup(props,ctx){
//router是全局路由对象,route= userRoute()是当前路由对象
let route = useRoute();
let num = route.query.num;
//let num = route.params.num;
return{
num
}
}
})
</script>
<style scoped lang='scss'>
</style>
欢迎关注前端早茶,与广东靓仔携手共同进阶
前端早茶专注前端,一起结伴同行,紧跟业界发展步伐~
公众号作者:广东靓仔