Home

Issue: 1029

How generate many computed propertys?

[issue link]

In my application, there are many similar properties that are computed. They differ only by name and default value

filter_pages: {
  get () {
    return this.$store.state.currentUser.options['filter_pages'] || this.pages.map(p => p.id)
  },
  set (value) {
    this.$store.dispatch('currentUser/setOptions', {options: {name: 'filter_pages', value}})
  },
},
filter_types: {
  get () {
    return this.$store.state.currentUser.options['filter_types'] || this.types[0]
  },
  set (value) {
    this.$store.dispatch('currentUser/setOptions', {options: {name: 'filter_types', value}})
  },
}

How can you quickly generate many properties of the same type? I tried to create an analog function mapState

// store/currentUser.js
export function mapOptions (options) {
  const res = {}
  for (let name in options) {
    const defaultValue = options[name]
    res[name] = {
      get() { return this.$store.state.currentUser.options[name] || defaultValue },
      set(value) { this.$store.dispatch('currentUser/setOptions', {options: {name, value}}) }
    }
  }
  return res
}

But I do not know how, in this case, you can pass the default value, which depends on the component data

// component
computed: {
  ...mapOptions({
    filter_pages: /* ... */,
    filter_types: /* ... */,
  })
}
This question is available on Nuxt.js community (#c894)