keep-alive+动态路由传参

keep-alive 是 Vue 内置的一个组件,可以使被包含的组件保留状态,或避免重新渲染。(缓存组件)
使用场景:
例如在A组件内多个输入框中输入信息,此时需要跳转进入B组件进行操作,再返回A组件。若没有使用 keep-alive,则A组件内输入框中的信息都会被清空,因为A组件被重新渲染。使用 keep-alive,则会保留之前输入框中的信息

具体可参考,转至这位作者https://blog.csdn.net/Dax1_/article/details/121962888

动态路由传参

两种方式来传递动态参数:
(1)params //取参this.$route.params.id
(2)query //取参this.$route.query.id

params方式的传参

(1)使用router-link方式实现路由跳转
(2)、使用$router的方式进行路由的跳转

query方式的传参

(1)使用router-link方式实现路由跳转
(2)、使用$router的方式进行路由的跳转

总结:
1.params方法传参时,属性名必须跟配置路由时的动态参数名一致,否则报错,query不用配置
2.路由跳转使用 “router”;获取参数使用“route”
3.params和query方法中,to属性使用对象的方式,且params方式路由的引入只能用name,query方式路由的引入可以用name和path。
4.如果不在配置路由时用:id配置,则传的参数刷新页面后就取不到这个id了,就只是传一次参而已,配置后刷新后不失效

//index.js中配置路由信息  //使用冒号:绑定动态参数。
const routes = [{
    path: '/goods/:id',
    component: Goods
}]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Vue 3 中使用 TypeScript 和路由结合动态 keep-alive 缓存,你可以使用 Vue Router 和 `<keep-alive>` 组件来实现。 首先,确保你已经安装了 Vue Router 和 Vue 3 的相关依赖。然后,在路由配置中添加 `meta` 字段来指定需要缓存的组件。 ```typescript // router.ts import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'; const routes: Array<RouteRecordRaw> = [ { path: '/', name: 'Home', component: () => import('@/views/Home.vue'), meta: { keepAlive: true // 将需要缓存的组件设置为 true } }, // 其他路由配置... ]; const router = createRouter({ history: createWebHistory(), routes }); export default router; ``` 接下来,在根组件中使用 `<router-view>` 和 `<keep-alive>` 组件来实现动态缓存。 ```vue <template> <div> <router-view v-slot="{ Component }"> <keep-alive> <component :is="Component"></component> </keep-alive> </router-view> </div> </template> <script> import { onMounted, watch } from 'vue'; import { useRouter } from 'vue-router'; export default { setup() { const router = useRouter(); // 监听路由变化,判断是否需要缓存组件 watch( () => router.currentRoute.value, (to, from) => { if (to.meta.keepAlive && from.meta.keepAlive) { // 如果前后两个路由都需要缓存,则手动触发组件的生命周期钩子 const component = router.currentRoute.value.matched[0].components.default; component.__vccOpts && component.__vccOpts.activated && component.__vccOpts.activated(); } } ); // 在初次加载时手动触发根组件的生命周期钩子 onMounted(() => { const component = router.currentRoute.value.matched[0].components.default; component.__vccOpts && component.__vccOpts.activated && component.__vccOpts.activated(); }); } }; </script> ``` 在上面的示例中,我们在路由配置中将需要缓存的组件的 `meta.keepAlive` 设置为 `true`。然后,在根组件中使用 `<router-view>` 来渲染当前路由匹配的组件,并将其包裹在 `<keep-alive>` 组件中。 通过监听路由变化,我们可以判断前后两个路由是否都需要缓存。如果是,则手动触发组件的 `activated` 生命周期钩子,以确保组件被正确缓存和激活。 请注意,这里我们使用了 Vue 3 的 Composition API 来编写逻辑。确保你的项目已经配置了相关依赖并支持 Composition API。 希望这个示例对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值