Vue3.0路由 -- 学习笔记
1.在新建项目时选择Router
之后打开项目,就会在项目目录下有如下:router文件夹下配置路由,views里编辑路由跳转页面
2.路由的路径配置都在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
3.页面里进行路由跳转
<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>
4.接收参数
<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>