IT이야기

Vue 라우터 조건부 리디렉션?

cyworld 2022. 3. 13. 11:01
반응형

Vue 라우터 조건부 리디렉션?

나는 라우터 링크가 서버로부터 받은 데이터를 기반으로 하는 간단한 Vue 앱을 만들려고 하는데, 데이터는 이와 같다.

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

지금 내가 이루고자 하는 것은 동적 라우터 링크 요소들을 사용하는 것이다.window.location.href만약url필드는 null이 아니다. 그렇지 않으면 나는 그것이 라우터 링크이기를 원한다.현재 내가 한 일이 잘 안 풀리고, 계속 이렇게 오류를 던진다.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 앱이 다운돼서 아무것도 안 뜨는데, 내가 이걸 할 수 있는 방법이 없을까?

torouter-link링크 이름만 사용해야 한다.

이것을 하기 위해서는 맞춤법이 필요 없다.더 좋은 방법은<a>URL 리디렉션의 경우 태그:

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

별도의 기능을 사용하여 구현을 유지하려면 다시 사용<a>대신에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}`);
    }
  }
}

참조URL: https://stackoverflow.com/questions/63652099/vue-router-conditional-redirect

반응형