Search code examples
javascriptvue.jsvuejs2frontendvuejs3

VueJS: Is it possible to use spread operator for computed properties?


I just wonder if I could do the code below less ugly.

In the component I have a property person. I'd like to use fields of the person object in my template without prepending each field with person.something. But the only way I know is below.

This is what I have atm:

(Please consider the code below as just an example, it's not a real one)

{
  name: 'Demo',
  props: {
    person: {
      type: Object,
      default: {}
    }
  },
  computed: {
    firstName() {
      return this.person.firstName
    },
    lastName() {
      return this.person.lastName
    },
    age() {
      return this.person.age
    },
    gender() {
      return this.person.gender
    }
  }
}

This is what I want to have instead (kind of):

{
  name: 'Demo',
  props: {
    person: {
      type: Object,
      default: {}
    }
  },
  computed: {
    ...this.person // <-- something like this would be better if only it would work
  }
}

Some assumptions

I assume that things like this should be possible, because we have mapGetters of vuex:

 computed: {
    ...mapGetters({ something: SOMETHING })
  },

Solution

  • With Vue 3 or the Composition API plugin for Vue 2 you could use toRefs() to spread the prop value inside the setup hook:

    import { toRefs } from 'vue' // Vue 3
    // import { toRefs } from '@vue/composition-api' // Vue 2
    
    export default {
      name: 'Demo',
      props: {
        person: {
          type: Object,
          default: {},
        },
      },
      setup(props) {
        return {...toRefs(props.person)}
      },
    }
    

    More information about toRefs()