0

I have a product component in vue.js.

All the json in data() {} is fetched from an api

I'd like to be able to set each key automatically from the fetched json insteach of having

I'm trying to achieve

data() {
  return {
    id: "1",
    sku: "g500",
    brand: "gildan"
  }
}

Instead Of This

data() {
  return {
    product: {
      id: "1",
      sku: "g500",
      brand: "gildan"
    }
  }
}

The vue.js method I'm using to set my data looks simulare to this... (actually data object has many more keys)

setData(product) {
  this.id = product.id;
  this.brand = product.brand;
  this.sku = product.sku;
}

is there a way I can make a method where I dont have to list out each "this.[key]"

Reason why I'm trying to create a function for this is because I want to use it as a global function and I dont want it to break if anything changes as I configure the database.

Thank you!!!

glweems
  • 3
  • 3
  • I didn't test, but you could try to use `this.$data = product` in `setData()` – ljubadr Jan 10 '19 at 17:20
  • Or `Object.assign(this.$data, product)` – ljubadr Jan 10 '19 at 17:22
  • app.js:5565 [Vue warn]: Avoid replacing instance root $data. Use nested data properties instead. found in ---> at resources/js/views/Product.vue at resources/js/Prepress.vue – glweems Jan 10 '19 at 17:46
  • 1
    In `setData()` you could use `for in`. `for (var key in product) { if (!product.hasOwnProperty(key)) continue; this[key] = product[key] }` – ljubadr Jan 10 '19 at 18:08

0 Answers0