vue default array prop

Vue Default Array Prop

If you are working with Vue.js components and want to specify an array prop, you may also want to set a default value for it. This can be done easily in Vue by setting a default value for the prop in the component definition.

For example, let's say we have a component called "MyComponent" that takes an array prop called "items". We can set a default value for this prop by adding a "default" property to the "props" object in the component definition:


Vue.component('MyComponent', {
  props: {
    items: {
      type: Array,
      default: function () {
        return []
      }
    }
  }
})

In this example, we are setting the default value of the "items" prop to an empty array. Now, if the "items" prop is not passed to the component, it will default to an empty array.

You can also use a shorthand syntax to set default values for props. Instead of using the "default" property, you can set the default value directly on the prop definition:


Vue.component('MyComponent', {
  props: {
    items: {
      type: Array,
      default: []
    }
  }
})

This does the same thing as the previous example, but uses a shorthand syntax to set the default value.

It's important to note that when setting default values for array props, you should always return a new instance of the array. This is because Vue uses object references to track changes to props, so if you use a reference to an existing array as the default value, it can lead to unintended behavior where changes to the prop affect the default value.

For example, if you set the default value of an array prop to an empty array like this:


Vue.component('MyComponent', {
  props: {
    items: {
      type: Array,
      default: []
    }
  }
})

And then modify the "items" prop in the component like this:


this.items.push('new item')

The default value of the "items" prop will also be modified, since it is referencing the same array instance. To avoid this, you should always return a new instance of the array in the default value function:


Vue.component('MyComponent', {
  props: {
    items: {
      type: Array,
      default: function () {
        return []
      }
    }
  }
})

By returning a new instance of the array, any changes to the "items" prop will not affect the default value.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe