TommyD
TommyD

Reputation: 1043

Vue custom Directive - object properties undefined

I have a custom Vue directive to show/hide an element based on a role.

Vue.directive('role', (el, binding, vnode ) => {
  const modifiers = binding.modifiers
  const roles = vnode.context.$store.state.roles;

  if (!roles.includes(binding.value) ||  (roles.includes(binding.value) && modifiers.not)) {
    el.style.display = 'none';
    vnode.elm.parentElement.removeChild(vnode.elm)

  }
})

This is the template and is in a v-for. They don't exist for admin users, I have

  <span
    v-role="'admin'"
  >
     {{ user.firstName }}, {{ user.lastName  }}
  </span>

The issue I am having is either using displaying none or removing the child still throws the error

Cannot read property 'firstName' of undefined

I can do a check for the property in the template but is there a way just not to render it if it does not exist?

Upvotes: 0

Views: 458

Answers (1)

IVO GELOV
IVO GELOV

Reputation: 14259

You should simply add safeguards:

  <span v-role="'admin'">
     {{ (user || {}).firstName }}, {{ (user || {}).lastName  }}
  </span>

Upvotes: 1

Related Questions