首页 > 解决方案 > Vue3中API的对象解构

问题描述

我想将数据从 API 放到 Vue 状态。什么是快速的方法来做到这一点?

getProjectData(id) {
      axios.get(`/api/project/${id}`).then((res) => {
        console.log(res)
        /* I don't want to manually assign the value one by one (since the name is the same, there should be a quick way */
        this.formState.name = res.data.projects.name
        this.formState.stage = res.data.projects.stage
        this.formState.status = res.data.projects.status
        this.formState.description = res.data.projects.description
        this.formState.stations = res.data.projects.stations
      });
    },

标签: javascriptobjectvuejs2state

解决方案


您可以使用扩展运算符来实现它:

this.formState = {...res.data.projects}

需要指出的是,这些属性是浅拷贝的。如果属性值是一个对象,对它所做的任何修改都将反映在该res.data.projects对象中。


推荐阅读