【问题标题】:Conditional rendering: comparing the result of async function in v-if条件渲染:比较v-if中async函数的结果
【发布时间】:2019-01-08 01:57:13
【问题描述】:

我有一个用于侧边栏的Vue 组件,其模板定义为:

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;
    }
  }
});

为简洁起见,删除了一些代码。
当我访问 /Profile/GetUserInfo 时,我得到一个 JSON 作为回报,它正确地返回了我 true 但 adminMenu 没有显示,我想知道为什么。看来v-if 是我搞砸的地方。我也尝试将 adminMenu 更改为 v-if="checkIfUserIsAdmin() == 'true'",但它仍然不起作用。

【问题讨论】:

  • 使用 watch/data 属性而不是 v-if="async function"

标签: javascript vue.js vue-component axios


【解决方案1】:

您需要等待方法的结果。

首先你需要在组件挂载时运行checkIfUserIsAdmin方法。 在checkIfUserIsAdmin 方法中,您需要将查询结果存储在adminMenuDisplay 变量中,然后您可以在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();
  }
});

【讨论】:

  • 完美运行。得益于此,我现在对组件生命周期有了更好的了解。
猜你喜欢
  • 2020-08-22
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 2023-01-17
  • 2020-12-20
  • 2019-10-07
  • 1970-01-01
相关资源
最近更新 更多