【问题标题】:Run computed function after mounted - VUE安装后运行计算函数 - VUE
【发布时间】:2018-05-26 23:39:00
【问题描述】:

我正在尝试运行一个函数,该函数需要我从 mount 方法返回的一些数据。现在我尝试使用computed 创建函数,但不幸的是,对于这种情况,计算在mounted 之前运行,所以我没有该函数所需的数据。这是我正在使用的:

    computed: {
      league_id () {
        return parseInt(this.$route.params.id)
      },
      current_user_has_team: function() {
        debugger;
      }
    },
    mounted () {
      const params = {};

      axios.get('/api/v1/leagues/' +this.$route.params.id, {
        params,
        headers: {
          Authorization: "Bearer "+localStorage.getItem('token')
        }
      }).then(response => {
        debugger;
        this.league = response.data.league
        this.current_user_teams = response.data.league
      }).catch(error => {
        this.$router.push('/not_found')
        this.$store.commit("FLASH_MESSAGE", {
          message: "League not found",
          show: true,
          styleClass: "error",
          timeOut: 4000
        })
      })
    }

如您所见,我在名为current_user_has_team 的计算函数中有debugger。但我需要从 axios 调用中返回的数据。现在我在调试器中没有数据。我应该使用什么回调来利用从网络请求返回的数据?谢谢!

【问题讨论】:

  • 您在current_user_has_team 中使用的是this.league 还是this. current_user_teams?如果是,则当数据从 axios 调用返回时,应自动重新计算此计算属性

标签: javascript vue.js


【解决方案1】:

如果您的计算属性 current_user_has_team 依赖于在 axios 调用之后才可用的数据,那么您需要:

  1. current_user_has_team 属性中,如果数据不可用,则返回一个合理的默认值。
  2. 在 axios 调用完成且数据可用之前,请勿从您的模板(限制为 v-if)或其他任何地方访问 current_user_has_team

这取决于您希望组件在“加载”情况下的行为方式。

【讨论】:

    【解决方案2】:

    如果您的行为是同步的,您可以使用beforeMount 而不是mounted 在计算计算属性之前运行代码。

    【讨论】:

      猜你喜欢
      • 2019-01-05
      • 2021-11-15
      • 2021-01-16
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-12
      • 2012-11-11
      相关资源
      最近更新 更多