【问题标题】:Vue router conditional redirect?Vue路由器条件重定向?
【发布时间】:2020-12-18 11:15:13
【问题描述】:

我正在尝试构建一个简单的 Vue 应用程序,其中路由器链接将基于从服务器接收到的数据,数据是这样的。

id: 1
path: "category_image/About.jpg"
slug: "about"
subtitle: null
title: "About Us"
url: "http://archeoportal.loc/page/about"

现在我要实现的是动态路由器链接元素,如果url 字段不为空,则将使用window.location.href,否则我希望它只是一个路由器链接。目前我所做的不起作用,它不断抛出像TypeError: Cannot read property 'redirect' of undefined 这样的错误。这是我的 Vue 文件的样子

<router-link
  :to="this.redirect(category.url !== null ? category.url : category.slug, category.url !== null ? true : false)"
  class="grid-item"
  v-bind:key="category.id"
  v-for="category in this.categories"
>
    <div class="category-title py-4">
      <h2>{{ category.title }}</h2>
      <p>{{ category.description }}</p>
    </div>
  <img :src="`/storage/${category.path}`" />
</router-link>

如您所见,我正在使用自定义方法来处理我的方法中的内容,类似于这样

methods:{
  redirect(url, window){
    if(window == true){
      window.location.href = url;
    }else{
      this.router.push('url');
    }
  }
}

但是我的 Vue 应用程序崩溃并且没有显示任何内容,有什么方法可以实现吗?

【问题讨论】:

    标签: javascript vue.js vue-router


    【解决方案1】:

    router-link 中的to 应该只取链接的名称。

    您不需要自定义方法来执行此操作。更好的方法是在 url 重定向的情况下使用 &lt;a&gt; 标签:

    <div 
      v-for="category in this.categories"
      :key="category.id"
    >
      <a 
        v-if="category.url"
        :href="category.url"
      >
        <div class="category-title py-4">
          <h2>{{ category.title }}</h2>
          <p>{{ category.description }}</p>
        </div>
      </a>
      <router-link
        v-else
        :to="`/${category.slug}`"
        class="grid-item"
      >
        <div class="category-title py-4">
          <h2>{{ category.title }}</h2>
          <p>{{ category.description }}</p>
        </div>
        <img :src="`/storage/${category.path}`" />
      </router-link>
    </div>
    

    如果您想使用单独的函数保留实现,请再次使用&lt;a&gt; 而不是router-link,如下所示:

    <a
      @click="redirect(category.url !== null ? category.url : category.slug, category.url !== null)"
      ...
    >
    
    methods: {
      redirect(url, isRedirect) {           
        if (isRedirect === true) {
          window.open(url);
        } else {
          this.router.push(`/${url}`);
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-09
      • 2017-07-21
      • 2018-04-13
      • 1970-01-01
      • 2019-02-21
      • 2019-06-28
      • 2022-08-19
      • 2021-12-17
      相关资源
      最近更新 更多