【问题标题】:Vuejs computed function returning unexpected outputVuejs计算函数返回意外输出
【发布时间】:2020-07-31 12:01:31
【问题描述】:

我正在尝试将 vue JS 中的道具的值设置为我在另一个类中的函数的输出。但是,当我调用此函数时,将返回函数的实际代码,而不是该函数的输出。这是我的代码以及我所指的屏幕截图。

在我的模板中

<nav>
      <ul>
          <li><router-link to="/games">All Games</router-link></li>
          <li><modal-deposit>Deposit</modal-deposit></li>
          <li @click="logout"><router-link to="/">Logout</router-link></li>
          <li>Balance {{ updateBalance }} </li>
      </ul>
</nav>

默认导出内

computed: {
    updateBalance: function(){
      return WalletService.getBalance;
    }
}

在 WalletService.js 中

class WalletService{
    //Get the balance from our logged in wallet
    static getBalance(){
        axios.get(url + decoded.email).then((res)=> {
            console.log(res.data[0].balance);
            return res.data[0].balance;
        })
    }
}

我想要 res.data[0].balance 中的值,但我不确定它为什么返回实际代码。我想补充一点,我还在学习 vuejs,在此之前没有使用过任何响应式框架。我曾尝试使用 watch: 而不是 computed: 但这会破坏 prop 值,表明它在渲染期间被引用,但未定义。即使我在 export default 的 data() 部分声明它。

【问题讨论】:

  • @KevynKlava 所以我切换到 asyncComputed 并引用了 Data() 中的道具,但是该值永远不会从 Data() 更新
  • 对不起,我忘了你必须安装 vue-async-computed
  • 我将准备一个示例,以便对您有所帮助,请稍等

标签: javascript vue.js


【解决方案1】:

如果你可以使用async/await ES6 特性:

在我的模板中

<nav>
      <ul>
          <li><router-link to="/games">All Games</router-link></li>
          <li><modal-deposit>Deposit</modal-deposit></li>
          <li @click="logout"><router-link to="/">Logout</router-link></li>
          <li>Balance {{ updateBalance }} </li>
      </ul>
</nav>

默认导出内

computed: {
    updateBalance: function() {
      return WalletService.getBalance();
    }
}

在 WalletService.js 中

class WalletService{
    // Get the balance from our logged in wallet
    static async getBalance() {
      const res = await axios.get(url + decoded.email);
      console.log(res.data[0].balance);
      return res.data[0].balance;
    }
}

【讨论】:

    【解决方案2】:

    可以使用 before mount 方法更新 balance 并将 balance 的实际值存储在一个变量中

    new Vue({
      el: "#app",
      data: {
        balance: 0
      },
      beforeMount: function() {
        fetch('https://jsonplaceholder.typicode.com/todos/1')
          .then(response => response.json())
          .then(c => {console.log(c); return c})
          .then(value => this.balance = value.userId)
      },
      
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <nav>
          <ul>
              <li>Balance {{ balance }} </li>
          </ul>
      </nav>
    </div>

    【讨论】:

    • 好的,所以从一些混乱的 beforeMount 和@BTL 的建议中,我得到了返回的值 \o/ 但是有一个问题。如果我以 User1 身份登录,他们的余额显示为 50。然后我注销并以新用户身份登录。在我手动刷新浏览器之前,User1 的余额仍然显示,因此该值似乎不会在路线更改时更新。具体来说,导航到路线时似乎没有触发 beforeMount 函数。知道那可能是什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-10
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多