let activePath = ref('/home'); watch(()=>router.currentRoute.value.path,(newVal)=>{ activePath.value = newVal; },{immediate:true})
时间: 2024-03-28 20:37:24 浏览: 11
这段代码是用Vue3的响应式编程方式实现了一个路由监听器。当路由变化时,watch函数会监听到currentRoute的变化,并将新的路由值赋给activePath变量,从而实现动态更新当前激活的路径。其中,ref函数用于创建一个响应式的变量,而watch函数则用于监听变量的变化。immediate:true表示在初始化时立即执行监听器函数。
相关问题
<div class="top"> <router-link to="/PC/index"> <img src="/static/images/login/logo2.png" alt="图片" /> </router-link> <h2>欢迎登录</h2> </div>
这是一段 HTML 代码,包含一个 div 元素和两个子元素。div 元素的 class 属性为 "top",子元素包括一个 router-link 元素和一个 h2 元素。router-link 元素使用了 Vue.js 的路由功能,指向路径为 "/PC/index" 的页面。h2 元素显示了文本内容 "欢迎登录"。其中,img 元素是 router-link 元素的子元素,显示了一个图片,其路径为 "/static/images/login/logo2.png"。
watch( () => router.currentRoute, (to, from) => { // to: 当前路由对象 // from: 上一个路由对象 console.log("路由变化", to, from); } )没有效果
如果`watch`函数无法监听路由变化,可能是因为`currentRoute`对象是一个响应式对象,需要使用`.value`属性才能获取到其值。因此,可以将`watch`函数修改为如下形式:
```javascript
import { watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
export default {
setup() {
let router = null
onMounted(() => {
router = useRouter()
watch(() => router.currentRoute.value, (to, from) => {
// to: 当前路由对象
// from: 上一个路由对象
console.log('路由变化', to, from)
})
})
return {}
}
}
```
在上述代码中,我们使用`watch`函数监听`currentRoute.value`属性的变化。这样,当路由发生变化时,`watch`函数就会执行回调函数了。