代码之家  ›  专栏  ›  技术社区  ›  asanas

VueJS:页面加载时自动重定向

  •  0
  • asanas  · 技术社区  · 6 年前

    例如:

    http://localhost:3000/redirecting/?link=http://externalsite.com

    1. 我知道如何从URL读取link参数。所以,我来拿这个。
    2. 然后我有状态的用户身份验证数据,我可以在计算属性中获得它。
    3. 现在,基于用户对象,我可以确定用户是否登录。
    4. 如果他没有登录,请重定向到登录页面。如果用户已登录,请重定向到外部链接(这是问题区域)。

    请注意,没有点击或任何东西。一旦用户访问此页面,就会发生重定向。如果我们能显示一条消息“重定向…”一秒钟就更好了。

    3 回复  |  直到 6 年前
        1
  •  2
  •   asanas    6 年前

    inNuxt的自定义路由也起了作用。但是我用了下面的方法。这也帮助我播种'重定向…'的消息前一秒钟重定向。

    <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>
    
        2
  •  0
  •   Abana Clara    6 年前

    您必须在页面加载后立即执行检查。现在,不管你的登录算法是什么,你都应该有办法在前端访问这个状态。

    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来处理这个问题,因为这与用户界面无关。

        3
  •  0
  •   channasmcs    6 年前

    你可以用它 导航防护装置 . 您不需要查看任何文件。只需使用路由文件

    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()
          }
      }
    }
     ]
    })