使用Vue.js体验导航栏闪烁

时间:2017-11-02 09:48:47

标签: vue.js vuex

在功能被评估为真或假之前,我的导航栏中出现了闪烁。

需要评估的功能如下:

export default {
  methods: {
    isAuthenticated () {
      return this.$store.state.user.authenticated
    }
  },
  data: () => {
    return {
      unauthenticated: [
        {
          title: 'Link1',
          url: '/link1'
        },
        {
          title: 'Link2',
          url: '/link2'
        },
        {
          title: 'Link3',
          url: '/link3'
        }
      ],
      authenticated: [
        {
          title: 'otherLink1',
          url: '/otherlink1'
        },
        {
          title: 'otherLink2',
          url: '/otherlink2'
        },
        {
          title: 'otherLink3',
          url: '/otherlink3'
        }
      ]
    }
  }
}

导航栏有以下内容:

<template v-if="isAuthenticated()">
  <b-nav is-nav-bar>
    <b-nav-item v-for="nav in authenticated" :key="nav.title" :href="nav.url">{{nav.title}}</b-nav-item>
  </b-nav>
</template>
<template v-else>
  <b-nav is-nav-bar>
    <b-nav-item v-for="nav in unauthenticated" :key="nav.title" :href="nav.url">{{nav.title}}</b-nav-item>
  </b-nav>
</template>

但是,当我点击导航时,未经身份验证的链接会显示一秒钟,然后经过身份验证的链接会显示,好像isAuthenticated()功能尚未评估。我该怎么做才能消除这种闪烁?

我的商店文件(user.js)文件如下所示:

export const state = () => ({
  headers: {},
  profile: {}
})

export const mutations = {
  updateHeaders (state, headers) {
    state.headers.access_token = headers['access-token']
    state.headers.token_type = headers['token-type']
    state.headers.client = headers['client']
    state.headers.expiry = headers['expiry']
    state.headers.uid = headers['uid']
    if (state.headers.expiry == null) {
      state.authenticated = false
    } else {
      let timeToExpiry = new Date(state.headers.expiry * 1000)
      let now = new Date()
      state.authenticated = now < timeToExpiry
    }
  },
  signout (state) {
    state.headers = {}
    state.profile = {}
  }
}

登录/注销方法通过对Rails应用程序的API调用发生。 Devise gem处理剩下的事情。

提前致谢!

修改

我正在使用Nuxt.js作为布局/页面/组件,因此我认为链接提交时引用了this.$router.push(url)

b-nav代码来自Bootstrap Vue

2 个答案:

答案 0 :(得分:0)

单击其中一个链接时执行的代码未说明,我假设它类似于this.$router.push(url)。如果是这种情况,您可能已将导航栏包含在<router-view>中,因此当您切换当前路线时,<router-view>内的组件会重新渲染,因此导航栏会闪烁。将它们移出<router-view>应该解决这个问题。

编辑:所以OP还没有使用vue-router,在这种情况下,要么手动更改根组件的数据以使除导航之外的其他部分发生更改,要么添加{{1并使用vue-router导航,以便this.$router.push()之外的部分不会更改或闪烁。

无论如何,我们需要使用vue组件让vue只重新呈现视图的一部分,而只需按<router-view>或某些东西导航就会破坏所有内容并重新构建它们,因此闪烁。

答案 1 :(得分:0)

使用bootstrap-vue时,有两种方法可以添加链接到导航栏。一种是绑定到cut -d $'\t' -f 2 属性,这会创建一个常规的html锚点。另一种是使用:href属性,它创建一个与vue-router交互的链接。

:to

没有理由在此处使用 <b-navbar-nav v-if="isAuthenticated()"> <b-nav-item v-for="nav in authenticated" :key="nav.title" :to="nav.url">{{nav.title}}</b-nav-item> </b-navbar-nav> <b-navbar-nav v-if="!isAuthenticated()"> <b-nav-item v-for="nav in unauthenticated" :key="nav.title" :to="nav.url">{{nav.title}}</b-nav-item> </b-navbar-nav> 标记来封装。另请注意,不推荐使用'is-nav-bar'。请参阅here,注意弃用。