V-Show指令函数无限循环

时间:2019-02-03 16:52:51

标签: vuejs2

我正在v-if指令内调用函数,以根据用户角色在边栏中隐藏链接。 由于异步地从远程数据库中检索了用户,所以有时getUser()函数中的用户信息有时会返回null,因此我想到了设置几秒钟的超时时间来等待用户信息可用,并且然后再次运行检查用户权限。

当我添加一行这样的代码时,该函数进入无限循环->

html

<SidebarNavTitle :key="item.key ? item.key : index" :name="item.name" 
:classes="item.class" :wrapper="item.wrapper"
                         :ref="item.name"
                         v-show="checkUserRole(item.disableFor, item) === true" />

javascript

checkUserRole (disableFor, item) {
  if (disableFor && disableFor.length > 0) {
    // let roles = disableFor.slice(' ')
    if (this.getUser()) {
      if (disableFor.indexOf(this.getUser().role) != -1) {
        // console.log('show false')
        return false
      } else {
        // console.log('show true')
        return true
      }
    } else {
      console.error('Sidebarnav error. Not able to get loggedUser')
      // when I just add this line of code, the checkUserRole function, keeps getting called in an infinite loop, and doesn´t enter the setTimeout
      this.checkAgainElements.push([disableFor,item]) 
      // debugger
      if (this.checkAgain) {
         this.checkAgain = false
         // let _ = this
         setTimeout( () => {
           // _.checkAgainFunction()
         }, 7000)
      }
      return false
    }
  }
  return true
},

    asyncComputed:{
    asyncLoggedUser(){
      console.log('inside async user getter store sidebarnav')
      return this.$store.getters.user
    }
  },
  },
  data () {
    return {
      user: this.asyncLoggedUser,
      checkAgainElements: [],
      checkAgain: true,
      doubleCheck:true,
    }
  },

getUser() {
  if (!this.user) {
    this.user = JSON.parse(sessionStorage.getItem('loggedUser'))
  }
  return this.user
},

实际结果

infinite loop

我希望函数迭代所有导航标题并输入settimeout 我在这里可能会错过什么?

1 个答案:

答案 0 :(得分:0)

因此,解决方案非常简单...实际上只是要在v-show指令中添加以检查用户对象是否可作为第一个条件,然后,如果可用,请运行checkUserRole函数,例如{{ 1}}

非常简单...

希望有人对此代码有帮助。...=>