挂载后运行计算函数 - VUE

Bit*_*ise 9 javascript vue.js

我正在尝试运行一个函数,该函数需要从挂载方法中获取的一些数据。现在我尝试使用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
        })
      })
    }
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我debugger在计算函数中调用了current_user_has_team函数。但是我需要从 axios 调用中返回的数据。现在我在调试器中没有数据。我应该使用什么回调,以便我可以利用从网络请求返回的数据?谢谢你!

Dec*_*oon 15

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

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

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


Ben*_*Ben 5

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