我有一个Vue应用程序,当用户访问特定页面时,我想自动重定向到外部页面。我不确定该怎么做。
例如:
http://localhost:3000/redirecting/?link=http://externalsite.com
请注意,没有点击或任何东西。用户访问此页面后,应立即进行重定向。如果我们能再显示一则消息“正在重定向...”,那就更好了。
更新:我正在使用Nuxt / Vue。
答案 0 :(得分:0)
页面加载后,您必须立即执行检查。现在,无论您使用哪种登录算法,都绝对应该以某种方式在前端访问此状态。
function getLoginStatus(){
//do something, get login status from server whatsoever
return status; //boolean
}
function redirect(){
const url = window.location.search.split("?link=")[1];
const externalurl = 'https://foo.com';
//get url, parse, etc etc
//check login status
if(getLoginStatus()){
window.location.href = externalurl;
}
else {
window.location.href = 'login.html';
}
}
window.onload = function(){
redirect();
}
现在您要做的就是组织一下,使其适合您的vue代码或您使用的任何代码结构。您可以使用路线之类的东西。我本人甚至都不会使用Vue来处理此问题,因为这与用户界面无关。
答案 1 :(得分:0)
您可以使用 Navigation Guards 进行操作。您不需要任何查看文件。只需使用路由文件
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// check link param exit using route param method
if (link exit) {
// window.location.href = add redirtect url
} else {
next()
}
}
}
]
})
答案 2 :(得分:0)
Nuxt中的自定义路由也起作用。但是我采用了以下方法。这也帮助我在重定向之前播出了“正在重定向...”消息一秒钟。
<template>
<div>
<p>Redirecting...</p>
</div>
</template>
<script>
export default {
mounted () {
const user = this.$store.state.auth.user
if (user !== null) {
if (this.$route.query.link) {
window.location.href = this.$route.query.link
} else {
window.location.href = '' // Some default link
}
} else {
window.location.href = '' // login page
}
}
}
</script>