Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 })
  },
like image 961
SpellSword Avatar asked Aug 05 '21 09:08

SpellSword


2 Answers

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'//vue3
//import {toRefs} from '@vue/composition-api'//vue 2

export default{
  name: 'Demo',
  props: {
    person: {
      type: Object,
      default: {}
    }
  },
setup(props){

return {...toRefs(props.person)}
}

}
like image 91
Boussadjra Brahim Avatar answered Oct 15 '22 22:10

Boussadjra Brahim


I see your point but what you want is not possible.

The main problem is this. We work with Options API. What is computed? An object that is passed into a Vue and Vue creates new instance with computed property for each function (or get/set pair) inside computed object. That means the spread operator is executed at the time component instance does not exist yet which means there is no this

mapGetters works because it's input are just static strings. If you had some static description of the Person object - for example some schema generated from Open API specification - you could create mapProperties helper and use it to generate computed props...

Edit: Yes, there is a way to create computed props dynamically in beforeCreate by modifying $options object - at least it was possible in Vue 2. Not sure about Vue 3. In both cases it is documented to be read only and Vue 3 is somehow more strict in forcing "read onlyness". However this is very different approach from the one in your question...

The approach is demonstrated for example here

like image 29
Michal Levý Avatar answered Oct 15 '22 23:10

Michal Levý