【问题标题】:VueJs, how to refresh the data that has been fetch through created functionVueJs,如何刷新通过创建函数获取的数据
【发布时间】:2021-06-27 05:30:34
【问题描述】:

我在 Promise 对象上使用“then”和“catch”函数,而不使用异步函数来实现简单和可管理的响应部分,而不是使用 await 和条件 if-else 然后检查状态 if 不是服务器端错误但是我对如何管理 Promise Object 的“then”方法以自动刷新已通过创建函数获取并使用过滤器在“then”方法中重新定义的数据而不再次获取后端的数据有点困惑.

export default {
  name: 'App',
  components: {
    Header,
    Tasks,
    AddTask
  },
  data() {
    return {
      tasks : [],
      showAddTask : false
    }
  },
  methods : {
    deleteTask(index) 
    {
        const that = this;
        const res = fetch(`api/tasks/${index}`, {
          method : "DELETE"
        });

        res.catch(e => alert("Error deleting task"));
        res.then(function() {
          
          /**
          * this is a part where I am a bit confused 
          **/

          that.tasks.filter(e => e.id !== index)

          /** 
          * I use this method but it is not working
          **/

          that.$forceUpdate();


        });

        return res;

    }, 
    async fetchTask()
    {
      const res = await fetch("api/tasks");
      const data = await res.json();
      return data;
    },
  },
  async created() {
    this.tasks = await this.fetchTask();
  }
}  

【问题讨论】:

  • that.tasks.filter( 不会改变数据。这是一个noop。没什么可刷新的,that.tasks 不变,可以调试。在一般情况下,$forceUpdate 是不必要的。

标签: javascript vue.js vuejs3


【解决方案1】:

Array.prototype.filter 返回原始数组的子集。它不会就地改变数组,因此您必须将filter 的返回值分配给this.tasks

另外,无需指定that = this。只需使用arrow functions 来捕获 Vue 实例上下文。

deleteTask() 应如下所示:

export default {
  methods: {
    deleteTask(index) {
      fetch(`api/tasks/${index}`, {
        method : "DELETE"
      }).then(() => {
        this.tasks = this.tasks.filter(e => e.id !== index)
      }).catch(e => alert("Error deleting task"));
    }
  }
}

demo

【讨论】:

    【解决方案2】:

    我注意到这里有几件事。

    第一,使用 async/await 时不需要 if-else。与 promise then/catch 等效的 async/await 是 try/catch 块:

    try {
        const res = await fetch(...);
        // Do something with res (response)
    } catch (err) {
        // Equivalent to promise catch, handle the error (err)
    }
    

    其次,如果您在当前回调中使用箭头函数,则无需捕获const that = this。而且您的语法很奇怪,理想情况下,您应该将 .then 和 .catch 链接起来:

    fetch(...)
        .then((res) => { // this is an arrow function
            this.tasks...
        })
        .catch((err) => { // again an arrow function
            // Handle the error
        });
    

    最后,Array.prototype.filter 返回一个包含过滤项的新数组。由于您没有使用 that.tasks.filter 的结果,因此实际上没有发生任何事情。相反,这样做:

    this.tasks = this.tasks.filter(...)
    

    【讨论】:

      猜你喜欢
      • 2021-04-25
      • 2018-04-19
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 2016-10-16
      相关资源
      最近更新 更多