简体   繁体   中英

Vue.js 2 Set all reactive properties from API call

I have a vue component with some properties eg.

import { getAPI } from "@/axios-api";
import { mapGetters, mapActions } from "vuex";
export default {
  name: "edit-profile-form",
  data() {
    return {
      first_name: "",
      last_name: "",
...

I also have an API call that will get these properties, which have exactly the same name eg.

{
   "first_name": "Jon",
   "last_name": "Doe"
}

Is there a way I can update both properties simultaneously? instead of doing

axios.get('/url/').then(res => {
  this.first_name = res.first_name;
  this.first_name = res.first_name;
});

Thanks

A quick way to copy those fields into your data is to use Object.assign() :

axios.get('/url/').then(res => {
  Object.assign(this.$data, res.data)
});

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM