首页 > 解决方案 > 有条件地在 $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>

标签: vue.jsvue-componentvue-routervuejs3

解决方案


更新:

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
        }
     }
  },

推荐阅读