vue-router4.0的食用方法

安装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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值