vue.js - 当我在 CREATED 挂钩中调用时,$route.name 和/或 $router.currentRoute.name 返回 null
问题描述
这是我的路由器
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/boys',
name: 'Boys',
component: () => import(/* webpackChunkName: "boys" */ '../views/Boys.vue')
},
{
path: '/girls',
name: 'Girls',
component: () => import(/* webpackChunkName: "girls" */ '../views/Girls.vue')
}
]
const router = new VueRouter({
mode: 'history',
linkExactActiveClass: "active__nav",
routes
})
export default router
这是我的整个组件,我放了整个代码以防万一
<template>
<div class="nav">
<ul>
<router-link v-for="(menuItem, i) in menu"
:key="menuItem.name"
:to="{name : menuItem.route}"
tag="li">
<p class="menu__item__name"
@mouseover="ft_hover($event, i, 20)"
@mouseleave="ft_hover($event, i, 0)"
@click="ft_click($event, i)">
{{ menuItem.title }}
</p>
<div class="animate__link" :style="menuItem.styleNavBar"></div>
</router-link>
</ul>
</div>
</template>
<script>
import MenuBar from "@/store/menu.js"; // importing menu with data
export default {
namespaced: true,
name: "TheNav",
data(){
return {
menu: MenuBar.navBar
}
},
methods: {
ft_click(e, i) // it just do animation on clicked Nav
{
this.menu.forEach( (el) => {
el.styleNavBar.width = 0 + '%';
el.active = false;
})
this.menu[i].active = true;
this.menu[i].styleNavBar.width = 80 + '%';
console.log(this.$route.name); // here I tried console log $route on click on menu
},
ft_hover(e, i, width) // it just do animation on hovered Nav
{
if(this.menu[i].active !== true)
this.menu[i].styleNavBar.width = width + '%';
}
},
created()
{
console.log(this.$router.currentRoute.name); // here is where I have issue
}
}
我想在第一次加载页面时获取路由器名称。如果我首先加载主页作为 localhost:8080 它返回“主页”,$router.currentRoute.name
或者$route.name
工作得很好。但是如果我加载 localhost:8080/girls 或 localhost:8080/boys 它会返回“null”。我尝试调试它。我有一个方法 ft_click 可以在点击的菜单上做一些动画,令我惊讶的是,它会在每次点击时打印出路由器名称,就像我在导航上所做的那样,除了它在后面一步打印它,所以如果我在主页上并点击Boys
它会打印Home
,然后如果我单击 Girls 它会打印Boys
。我不知道这是否与我的问题有关,但它至少给出了一个想法,即我的路线一切都很好,只是我想我不知道什么,这就是为什么它不起作用......
如果需要@store/menu
export default {
navBar: [{
title: 'Main',
route: 'Home',
styleNavBar: {
background: "#d1d8e0",
width: 0 + '%'
},
active: false
},
{
title: 'Girls',
route: 'Girls',
styleNavBar: {
background: "#f8c291",
width: 0 + '%'
},
active: false
},
{
title: 'Boys',
route: 'Boys',
styleNavBar: {
background: "#34495e",
width: 0 + '%'
},
active: false
}
]}
解决方案
推荐阅读
- reactjs - reactJS store 中的对象数组实现
- react-native - 如何修复错误元素类型无效预期字符串?
- python - 渲染在 vtkCommand 中创建的演员(回调)
- ajax - 将 HTML 字符串传递给我的控制器操作方法
- bash - 如何使用tail和grep并获取具有结果的文件名
- javascript - 单选按钮值正在打印“on”而不是它持有的值
- c++ - 这是缓存线程安全的通用实现(c++)吗?
- java - 带有 ASM 的 JVM INVOKESPECIAL 私有构造函数
- visual-studio-code - VSCode:不在项目中的文件在单独的窗口中打开
- php - 如何仅将 WordPress 的“the_title”过滤器用于帖子类型中的主标题?