【问题标题】:Why does this computed property return 'promise {<pending>'?为什么这个计算属性返回'promise {<pending>'?
【发布时间】:2021-06-02 17:55:40
【问题描述】:

我正在学习 Vue Js,我想开发一个小型应用程序,根据我在下拉列表中选择的内容,我可以使用它带来不同的数据。

我遇到的问题是,当我想(通过控制台)查看我通过计算属性带来的内容时,它会显示“promise {”,其中包含我想要处理的数据,但是处于“待处理”状态,我无法提取和使用它们。

这是我到目前为止开发的应用程序,根据输入的部分带来新闻:

    <template>
      <div>
        <div v-for="new in totalNews" :key="new.id">
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: "Home",
      data() {
        return {
          news: [],
        };
      },
      methods: {
        async getNews() {
    
         const param = this.$route.params.id;
          await this.axios
          .get("http://localhost:8080/api/v1/newsBySelection/" + id)
          .then((res) => {
            this.news = res.data;
          })
          .catch((error) => {
            console.log(error);
          });
      },
      computed: {
        totalNews() {
          let news = this.getNews()
          console.log(news);
          return news;
        },
      },
    };
    </script>

这是我在运行此应用程序时在控制台上得到的示例,正​​如您所看到的,每次我选择钻石的一部分时都会给我带来相应的消息,但是以承诺的形式:

https://i.postimg.cc/XqtHBZfL/imagenparasubir.png

我已经感谢任何形式的帮助!

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    getNews 是一个async 函数。虽然它实际上并没有return 任何东西,但它是异步的意味着它是Promise。你的totalNews 计算中发生的事情是你得到了代表this.getNews() 的promise 对象,所以你看到的行为是有道理的。您的计算可能不应该调用修改组件状态的方法。计算的重点是根据组件中的一个或多个属性返回一个值。

    改为在mounted 生命周期挂钩中调用this.getNews():

    <script>
      export default {
        name: "Home",
        // ...
        mounted() {
          this.getNews()
        }
      }
    </script>
    

    这里根本不需要使用计算对象,因为您只想显示数据中的所有对象。所以这就变成了:

    <template>
      <div>
        <div v-for="item in news" :key="item.id">
        </div>
      </div>
    </template>
    

    我还把new改成了item,因为new实际上是JavaScript中的一个关键字。

    更新

    如果您想根据用户选择进行过滤,则可以使用计算属性。像这样的东西:

    computed: {
      filteredNews() {
        return this.news.filter(item => item.someProperty === this.selectedOption);
      }
    }
    

    【讨论】:

    • 非常感谢您的回复。我在考虑计算属性,因为其目的是根据您从选项列表中选择的内容来显示某些数据。并且他们被动地展示自己
    • 我更新了我的答案,以展示如果您想过滤 news 项目,如何使用计算。
    【解决方案2】:

    您可能会从阅读 Promise 对象在概念上的工作原理中受益。

    根据您的目的,您可能会发现使用 .then() 方法很有用 - 它本质上会在承诺解决后回调内部代码。

    因为您使用的是异步函数,所以工作在单独的线程上。如果您试图在单独的线程中获取值,它不会知道数据何时加载。

    【讨论】:

      【解决方案3】:

      这并不是一个真正的 Vue 问题,而是一个通用的 Javascript 主题:异步调用如何工作,Promise 是什么以及async/await 如何简化语法。

      这是一个小 sn-p,向您展示了一个可能的解决方案,使用 Promise 来显示从 API 端点获得的项目列表:

      new Vue({
        el: "#app",
        data() {
          return {
            // we init a variable that is going to hold
            // the values that we expect to receive from
            // the API endpoint
            news: [],
          }
        },
        methods: {
          getNews() {
            fetch('https://jsonplaceholder.typicode.com/todos')
              .then(response => response.json())
              .then(json => {
                // the data is added to our component data
                // when it arrives from the API endpoint
                this.news = json
              })
          },
        },
        mounted() {
          // we query the API endpoint when the component
          // is mounted in the DOM
          this.getNews()
        }
      })
      <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
      <div id="app">
        <div v-for="article in news" :key="article.id">
          {{ article.title }}
        </div>
      </div>

      更新

      sn-p 中有一个隐含的东西:为什么它是使用Promise 的解决方案? sn-p 中的Promise 在哪里?

      [fetch] 返回一个 Promise,它解析为 Response 请求

      来源:MDN Fetch API

      这就是为什么我们可以在fetch() 之后使用.then() - fetch 总是返回一个Promise。

      【讨论】:

        猜你喜欢
        • 2020-09-30
        • 2020-07-25
        • 2021-09-10
        • 2021-01-03
        • 1970-01-01
        • 2018-08-19
        • 2021-01-11
        • 1970-01-01
        相关资源
        最近更新 更多