2

I have a Vue component for a sidebar with a template defined as:

Vue.component('navigation',{
  template:`
    <ul class="nav">
      <li v-if="checkIfUserIsAdmin() == true" id="adminMenu"></li>
      <li id="userMenu"></li>
  `,
  methods: {
    checkIfUserIsAdmin() {
      var result = false;
      axiosInstance.get("/Profile/GetUserInfo").then(userInfo => {
        result = userInfo.data.u.isAdmin;
      })
      .catch(userError => {
        swal({
          title: "Operational Platform",
          text: "Unable to retrieve user info"
        });
        result = false;
      });
      return result;
    }
  }
});

Some code was removed for brevity.
When I visit the /Profile/GetUserInfo I get a JSON in return that's properly returning me true but the adminMenu is not displaying and I'm wondering why. It seems that the v-if is the place that I've messed up. I've tried also changing the adminMenu to have v-if="checkIfUserIsAdmin() == 'true'" but it still didn't work.

1
  • uses watch/data property instead of v-if="async function" Commented Jul 31, 2018 at 15:49

1 Answer 1

2

You need to wait for the method's result.

First you need to run the checkIfUserIsAdmin method when the component is mounted. In checkIfUserIsAdmin method you need to store the result of the query in adminMenuDisplay variable and then you can watch this variable in v-if.

Vue.component('navigation',{
  template:`
    <ul class="nav">
      <li v-if="adminMenuDisplay" id="adminMenu"></li>
      <li id="userMenu"></li>
  `,
  data() {
    return {
      adminMenuDisplay: false
    };
  }
  methods: {
    checkIfUserIsAdmin() {
      var result = false;
      axiosInstance.get("/Profile/GetUserInfo").then(userInfo => {
        this.adminMenuDisplay = userInfo.data.u.isAdmin;
      })
      .catch(userError => {
        swal({
          title: "Operational Platform",
          text: "Unable to retrieve user info"
        });
        this.adminMenuDisplay = false;
      });
    }
  },
  mounted() {
    this.checkIfUserIsAdmin();
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly. I have now a better understanding of component lifecycle thanks to that.

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.