簡體   English   中英

Vue.js 路由器 - 條件組件渲染

[英]Vue.js router - conditional component rendering

 routes: [
{
  path: '/',
  name: 'home',
  get component(){
    if(Vue.loggedIn){
      return Home
    }else{
      return Login
    }
  }  
}

我添加了一個 getter 並且似乎工作正常,但是我在 if 語句中使用的任何變量或函數都是未定義的。 即使我嘗試使用全局原型。$var 和 mixin 函數仍然沒有成功。

我所需要的只是如果用戶登錄路徑“/”呈現儀表板視圖,如果沒有,則登錄呈現為“/”。

注意:我使用過 beforeEnter: 並且它工作正常。 但我不想重定向。

使用你的方法,這是我發現的工作:

routes: [
{
  path: '/',
  name: 'home',
  component: function () {
    if(loggedIn){
      return import('../views/Home.vue')
    }else{
      return import('../views/Login.vue')
    }
  }  
}

在我的應用程序中,我使用router.beforeEach來檢查用戶是否已登錄。我使用getter來檢查登錄狀態是否正確。 我還使用 meta 僅根據用戶是否登錄來顯示視圖。

我將此代碼應用到應用程序main.js的入口點

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!store.getters.loggedIn) {
      next({
        path: '/login',
      })
    } else {
      next()
    }
  } else if (to.matched.some(record => record.meta.requiresVisitor)) {
    // this route is only available to a visitor which means they should not be logged in
    // if logged in, redirect to home page.
    if (store.getters.loggedIn) {
      next({
        path: '/',
      })
    } else {
      next()
    }
  }
})

在我的router.js文件中,我將元設置為這樣

routes: [
  {
    // this is the route for logging in to the app
    path:      '/login',
    name:      'login',
    component: () => import(/* webpackChunkName: "login" */ './views/Login.vue'),
    props:     true,
    meta:      {
      requiresVisitor: true,
      layout:          'landing',
    },
  },
  {
    // this is the dashboard view
    path:      '/',
    name:      'dashboard',
    component: () => import(/* webpackChunkName: "dashboard" */ './views/Dashboard.vue'),
    meta:      {
      requiresAuth: true,
      layout:       'default',
      breadCrumb:   [
        { name: 'Dashboard' }
      ]
    }
  },
]

注意元對象。 如果您使用的是 vue devtools,您將看到這些參數可用於驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM