반응형
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 앱이 다운돼서 아무것도 안 뜨는데, 내가 이걸 할 수 있는 방법이 없을까?
to
에router-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
반응형
'IT이야기' 카테고리의 다른 글
create-react-app을 실 대신 npm으로 만드는 방법? (0) | 2022.03.13 |
---|---|
동일한 컴포넌트를 동적으로 반응 (0) | 2022.03.13 |
Laravel에서 Vue 라우터로 데이터를 전달하는 방법? (0) | 2022.03.13 |
어떻게 분단을 부동의 지점으로 강제할 수 있을까?0으로 반올림하는 중인가? (0) | 2022.03.13 |
개츠비의 소방 기지를 어떻게 초기화할까? (0) | 2022.03.13 |