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

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

目录

  • 前言
  • 1. unref
  • 2. Demo

前言

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

在这里插入图片描述

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)) // 10

console.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 string
  console.log('当前路由 name:', newName)
})

watch(() => route.path, (newPath) => {
  routePath.value = newPath
  console.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>

相关文章:

  • Spring Boot整合RabbitMQ
  • 蓝桥杯 - 每日打卡(类斐波那契循环数)
  • 17028djwcb
  • 探秘基带算法:从原理到5G时代的通信变革【六】CRC 校验
  • Spark(6)vm与centos虚拟机
  • DeepSeek API使用及私有化部署
  • 【向量数据库Weaviate】与ChromaDB的差异、优劣
  • week 2 - Branching - Arrays
  • JVM内存管理
  • 线程池的工作流程
  • VMware如何配置IP网络
  • java数据结构_Map和Set(一文理解哈希表)_9.3
  • 探索Elasticsearch:文档的CRUD
  • DeepSeek-OpenSourceWeek-第六天-Inference System Overview
  • Langchain解锁LLM大语言模型的结构化输出能力(多种实现方案)
  • Qt基础入门-详解
  • Linux配置虚拟机
  • AMD RDNA3 GPU架构解析
  • Oracle数据库安全防护体系构建与核心技术解析
  • Excel的行高、列宽单位不统一?还是LaTeX靠谱
  • 出现这几个症状,说明你真的老了
  • 燕子矶:物流网络中的闪亮节点|劳动者的书信②
  • 经济日报社论:书写新征程上奋斗华章
  • 投资者建议发行优惠套票给“被套”小股东,张家界:将研究考虑
  • 北方旱情持续,水利部:大中型灌区春灌总体有保障
  • 海尔智家一季度营收791亿元:净利润增长15%,海外市场收入增超12%