0

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?

3
  • you can simply use v-if as display:none will render it and apply the css. Commented Jul 7, 2020 at 14:30
  • I don't want to use v-if Commented Jul 7, 2020 at 14:32
  • Could you please post a workable demo in codepen or sandbox, that helps to get your problem clearly? Commented Jul 7, 2020 at 14:49

1 Answer 1

1

You should simply add safeguards:

  <span v-role="'admin'">
     {{ (user || {}).firstName }}, {{ (user || {}).lastName  }}
  </span>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.