vue.js - vuejs 路由器 - this.$route 在刷新时始终为空
问题描述
我正在尝试nav-active
根据您第一次直接访问 webapp 的 url 将类设置为正确的 nav 元素。
我有几条路线:
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: () => import('./views/Home.vue')
},
{
path: '/account',
name: 'account',
component: () => import('./views/Account.vue')
}
]
});
这是我的导航栏组件(NavBar):
export default {
name: 'NavBar',
components: {
NavLogo,
NavItem
},
data() {
return {
navItems: [
{ /* root navigation */
id: 0,
type: 'root',
name: 'home',
route: '/',
active: this.$route.name === 'home' },
{
id: 1,
type: 'root',
name: 'account',
route: '/account',
active: false
}
}
}
}
active
内部布尔值的状态navItems
决定了导航元素是否应该具有nav-active
类。我正在尝试使用当前路由来确定active
应该是真还是假,通过这种方式使用它:
active: this.$route.name === 'account'
但是,例如,我直接从以下位置进入此仪表板:http://localhost:8000/account
this.$route
的项目都是空的,路径始终是/
非常感谢帮助,谢谢
解决方案
默认情况下,您不会this.$route.name
使用这种方法跟踪更改。尝试创建一个解析为 的计算属性this.$route.name
,并在您的数据属性声明中使用它。实际上,您可以将整个内容粘贴到计算属性中,因为您不太可能更改它。
export default {
name: 'NavBar',
components: {
NavLogo,
NavItem
},
computed: {
routeName(){
return this.$route.name
},
navItems(){
return [
{ /* root navigation */
id: 0,
type: 'root',
name: 'home',
route: '/',
active: this.routeName === 'home' },
{
id: 1,
type: 'root',
name: 'account',
route: '/account',
active: false
}
]
}
}
}
推荐阅读
- javascript - 拖放 - 验证答案
- angularjs - 部署到服务器(GCP-AppEngine)后,无法在 AngularJs 中加载模块。错误:[$injector:unpr]
- r - 如何使用 data.table 找到组之间的线性回归?
- javascript - 如何根据一个条件返回两个值?
- tensorflow - 使用混淆矩阵值的 TensorFlow 自定义指标
- python - KERAS 在 docker 容器中添加第一层时随机卡住
- reactjs - Button doesn't disappear immediately; need to move mouse during animation using clip-path
- rabbitmq - spring.rabbitmq.addresses :负载均衡器地址与节点地址列表
- windows - 为管理员安装了不同版本的 npm;如何更新本地版本?
- android - 带有 *multiple* 的 Android 视图绑定
可能的?