安装vue-router4.0
npm install vue-router@4
创建组件
在components目录下创建两个文件即可
使用vue-router4
//router目录下的index.js
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
// 路由的懒加载
const routes = [
{ path: '/', component: () => import('../components/Home.vue') },
{ path: '/about', component: () => import('../components/About.vue') }
]
const router = createRouter({
// hash 或者 history 模式
// history: createWebHashHistory(),
history: createWebHistory(),
routes
})
// 全局路由守卫的方法跟vue-router3一样
//路由全局前置守卫
router.beforeEach((to,from,next)=>{
console.log('路由全局前置守卫', to, from);
next()
})
//路由全局后置守卫
router.afterEach((to,from,next)=>{
console.log('路由全局后置守卫', to, from);
next()
})
export default router
引入router
//main.js
import { createApp } from 'vue'
import App from './App.vue'
// 引入store router
import store from './store/store.js'
import router from './router/index.js'
createApp(App)
.use(store)
.use(router)
.mount('#app')
//App.vue
<template>
<div>
<router-link to="/">home</router-link>
<router-link to="/about">about</router-link>
<router-view></router-view>
</div>
</template>
区别不大,只是一些API改变成了函数的形式,在需要的时候引入即可
路由传参
a、query
在vue3
中取消了this
,所以要引入useRouter
,useRoute
函数,
//hello组件
<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
const toTest = () => {
// 可以使用对象的形式也可以使用字符串拼接
// router.push({path:'/test',query:{a:1}})
router.push('/test?a=1')
}
const count = ref(0)
</script>
//about组件
<script setup>
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()
console.log("query", route.query);//{a:1}
</script>
b、params传参
注意这里不能使用path属性,只能使用路由的name属性
//hello组件
<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
const toTest = () => {
// 注意这里不能使用path属性,只能使用路由的name属性
router.push({name:'Test',params:{a:1}})
}
const count = ref(0)
</script>
//about组件
<script setup>
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()
console.log("params", route.params);//{a:1}
</script>