Skip to content
Advertisement

Is there a way to destructure vue props so I don’t have to pass every single one in?

Simply put, I have a component

<Device>
v-for="device in devices" 
:key="device.name"
:device="device"
:name="device.name"
:number="device.number"
:type="device.type"
:status="device.status"
:plan="device.plan"
:plan_price="device.plan_price"
:health="device.health"
</Device>

I then define them in the props section of the component

props: {
        type: { type: String, default: "" },
        number: { type: String, default: "" },
        name: { type: String, default: ""},
        plan: { type: String, default: "" },
        plan_price: { type: String, default: "" },
        status: { type: Number, default: 0 },
        health: { type: Number, default: 0 },
    },

I am just wondering if there is a way to pass in :device=”device” without having to pass in every individual property. I also wanted to avoid having to use device.name device.property in the template within the component Thank you for any tips!

Advertisement

Answer

You can use v-bind to achieve some kind of object destructuring for props.

<Device>
  v-for="device in devices" 
  :key="device.id"
  v-bind="device"
</Device>
props: {
  type: { type: String, default: "" },
  number: { type: String, default: "" },
  name: { type: String, default: ""},
  plan: { type: String, default: "" },
  plan_price: { type: String, default: "" },
  status: { type: Number, default: 0 },
  health: { type: Number, default: 0 },
}

Demo: https://stackblitz.com/edit/vue-jngtah?file=src/App.vue

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement