vue.js - 有条件地在 $route 路径更改上显示 div 不起作用
问题描述
我是 Vue 的新手。我试图有条件地显示基于路由器链接的元素。如果链接在“/”或主页中,我想显示它,如果移动到任何其他链接,我想隐藏它。我尝试使用 watch 检查 $route 路径中的更改,但是我收到一个错误,它无法识别 this.$route。我想通过 v-if 和 v-else 触发一个变量来改变条件。这是在我的 app.js 文件中。谢谢你。
我收到错误 - App.vue?3dfd:89 Uncaught (in promise) TypeError: this.$route.path is not a function at Proxy.$route (App.vue?3dfd:89)
<template>
<div class="container">
<section class="projects">
<div class="toggleBtn">
<p v-if='home'>
<router-link to="/">projects</router-link> /
<router-link to="/experiments">experiments</router-link>
</p>
<p v-else>
<router-link class="back" to="/">BACK TO PROJECTS</router-link>
</p>
</div>
<router-view />
</section>
</div>
</template>
<script>
export default {
data() {
return {
home: true
}
},
mounted() {
this.animateTitle()
},
watch: {
$route(to, from) {
if (this.$route.path("/") || this.$route.path("/home")) {
this.home = true
} else {
this.home = false
}
}
},
methods: {
animateTitle() {}}
</script>
<style>
.toggleBtn {
position: relative;
width: 15vw;
margin-left: 78vw;
margin-top: 90vh;
border-radius: 20px;
z-index: 3;
}
.toggleBtn p {
font-family: 'Fantasque Italic';
line-height: 1;
white-space: nowrap;
font-size: 1.3rem;
}
.toggleBtn a {
text-decoration: none;
height: 20px;
color: rgb(141, 141, 141);
}
.toggleBtn a:hover {
text-decoration: line-through;
}
.toggleBtn a.router-link-exact-active {
color: black;
}
.back {
color: black;
}
</style>
解决方案
更新:
Maavia 建议的更好答案应该是这样的:
添加计算属性
computed: {
isHome() {
return this.$route.path == "/" || this.$route.path == "/home";
}
}
然后在模板中检查它的值:
<p v-if='isHome'>
<router-link to="/">projects</router-link> /
<router-link to="/experiments">experiments</router-link>
</p>
查看 if 语句。
watch: {
$route(to, from) {
if (this.$route.path == "/" || this.$route.path == "/home" ) {
this.home = true
} else {
this.home = false
}
}
},
推荐阅读
- ruby-on-rails - 在 ruby on rails 的不同页面上发布
- graphql - GraphQL 查询在 realations 上查找相等字段
- javascript - 浏览器加载相同的图像 2 次
- angular - Angular ActivatedRoute,探索 sconosciuto
- rest - 为首次登录创建用户记录/个人资料
- google-cloud-platform - 如何在不下载本地的情况下将图像从公共数据库传输到 Google Cloud Bucket
- php - 在类别页面的价格下添加产品重量
- php - 当php中没有内容时更改背景颜色
- java - 是否可以在 Artemis JMS 中插入一批消息
- angular - 使用量角器在带有 ag-grid 的角度站点上查找元素的问题