Search code examples
javascriptvue.jsvuexvuex-modules

Is there a way to pass attributes to Vue JS computed getter/setter?


I am trying to use computed property to bind my input fields with the Vuex Store. So I have Data Streams and each of them have specific input fields, they aren't fixed but managed from the admin section of the application, and I have to provide to the users functionality that user will select specific data stream and then inputs will be shown as received from the API.

I have tried to achieve that but here is my blocker. Computed properties (getters) cannot receive attributes so I cannot tell the vuex getter which data to return.

Please find bellow the code I have used, Is there some other way to achieve the same functionality?

I am using the next versions:

  • vue - 2.6.1
  • vuex - 3.6.2
  • vuetify - 2.5.6

Vue JS Component - Input fields

<v-text-field
    :key="input_index"
    v-model="data_stream_inputs[ds_index][input_index]"
    :label="input.name"
    :placeholder="input.placeholder"
></v-text-field>

Computed properties (not working properly)

computed: {
    data_stream_inputs: {
        get() {
            return this.$store.getters['ActivateAudienceStore/getDataStreamInputByIndex'],
        set(value) {
            this.$store.commit('ActivateAudienceStore/SET_DATASTREAM_INPUT_BY_INDEX', value)
        }
    }
}

Getter

export const getDataStreamInputByIndex = (state) => (payload) => {
    return state.data_delivery.datastreams[payload.data_stream].inputs[payload.index]
}

Solution

  • data_stream_inputs should be a function in order to receive arguments and be used like data_stream_inputs({ index: index1 })[index2], this doesn't play well with a writable computed.

    v-model doesn't have to be used where it's not straightforward, it can be desugared, e.g. in Vue 2:

    <v-text-field
        :value="$store.getters['someGetter']({ index: index1 })[index2]"
        @update:value="$store.commit('someMutation', $event)"
        ...