当前位置: 首页 > news >正文

Vue 3 中 unref 的作用与 Vue Router currentRoute 的知识

目录

  • 前言
  • 1. unref
  • 2. Demo

前言

🤟 找工作,来万码优才:👉 #小程序://万码优才/r6rqmzDaXpYkJZF

从实战中学习,了解一点点知识点

在这里插入图片描述

unref 主要用于解包 ref,特别是在 Vue Router 4 里,currentRoute 是一个响应式 ref,需要 .value 或 unref 来访问具体字段

1. unref

unref 是 Vue 3 提供的工具函数,可以解包 ref 值,即:

  • 如果传入的是 ref,返回 ref.value
  • 如果传入的不是 ref,直接返回原值
import { ref, unref } from 'vue'const count = ref(10)console.log(count.value) // 10
console.log(unref(count)) // 10console.log(unref('Hello Vue 3')) // 'Hello Vue 3' (非 ref 直接返回)

再者为什么 currentRoute 需要 unref?
为何要用unref来解析呢

在 Vue Router 4 里,useRouter().currentRoute 是一个 ref 对象,用于存储当前路由信息

const router = useRouter()
console.log(router.currentRoute) // 这是一个 ref 对象
console.log(router.currentRoute.value) // 访问当前路由信息

由于 currentRoute 是 ref,所以要获取 name、path 等字段时,可以使用:

const { name } = router.currentRoute.value

或者:

const { name } = unref(router.currentRoute)

它的实际应用放在监听当前路由变化,或者访问 name、path、meta 等字段

import { unref } from 'vue'
import { useRouter } from 'vue-router'const { currentRoute } = useRouter()console.log(unref(currentRoute)) // 打印完整的当前路由对象
console.log(unref(currentRoute).name) // 获取路由 name

2. Demo

具体小例子:

<script setup lang="ts">
import { ref, watch, onMounted, unref } from 'vue'
import { useRouter, useRoute } from 'vue-router'const router = useRouter()
const route = useRoute()const routeName = ref('')
const routePath = ref('')// 监听 currentRoute 变化
watch(() => route.name, (newName) => {routeName.value = newName as stringconsole.log('当前路由 name:', newName)
})watch(() => route.path, (newPath) => {routePath.value = newPathconsole.log('当前路由 path:', newPath)
})// 在 mounted 阶段输出初始值
onMounted(() => {console.log('完整的路由对象:', unref(router.currentRoute))console.log('当前路由 name:', unref(router.currentRoute).name)console.log('当前路由 path:', unref(router.currentRoute).path)
})
</script><template><div><h2>当前路由信息</h2><p>路由名称: {{ routeName }}</p><p>路由路径: {{ routePath }}</p></div>
</template>

http://www.mrgr.cn/news/93047.html

相关文章:

  • 物理竞赛中的线性代数
  • 服务器时间同步
  • PAT乙级真题 / 知识点(1)
  • Metal学习笔记七:片元函数
  • C++学习之C++初识、C++对C语言增强、对C语言扩展
  • 静态时序分析:SDC约束命令set_clock_jitter详解
  • 【实战 ES】实战 Elasticsearch:快速上手与深度实践-2.2.3案例:电商订单日志每秒10万条写入优化
  • vue videojs使用canvas截取视频画面
  • 基于 DataEase 的企业数据分析实践
  • 硅基流动nodejs流式输出
  • 使用vite创建vue3项目
  • T-SQL 语言基础: SQL 数据库对象元数据及配置信息获取
  • AMD RDNA3 GPU架构解析
  • (十 九)趣学设计模式 之 中介者模式!
  • 【算法】手撕二分查找
  • stm32 jlink烧录时写保护
  • HOW - 在Windows浏览器中模拟MacOS的滚动条
  • 私有云基础架构
  • 多个pdf合并成一个pdf的方法
  • easyExcel使用案例有代码