nahoj
nahoj

Reputation: 285

Vue 3 with Vuex 4

I'm using Vue 3 with the composition API and trying to understand how I can map my state from Vuex directly so the template can use it and update it on the fly with the v-model.

Does mapState works or something else to solve this issue? Right no I need to get my state by a getter, print it out in the template, and then do a manual commit for each field in my state... In Vue 2 with Vuex, I had this 100% dynamic

Upvotes: 0

Views: 439

Answers (2)

nahoj
nahoj

Reputation: 285

I've solved it!

Helper function:

import { useStore } from 'vuex'
import { computed } from 'vue'

const useMapFields = (namespace, options) => {
const store = useStore()    
const object = {}

if (!namespace) {
    console.error('Please pass the namespace for your store.')
}

for (let x = 0; x < options.fields.length; x++) {
    const field = [options.fields[x]]
    
    object[field] = computed({
        get() {
            return store.state[namespace][options.base][field]
        },
        set(value) {
            store.commit(options.mutation, { [field]: value })
        }
    })
}


return object
}

export default useMapFields

And in setup()

       const {FIELD1, FIELD2}  = useMapFields('MODULE_NAME', {
            fields: [
                'FIELD1',
                 etc…
            ],
            base: 'form', // Deep as next level state.form
            mutation: 'ModuleName/YOUR_COMMIT'
        })

Vuex Mutation:

    MUTATION(state, obj) {
        const key = Object.keys(obj)[0]
        state.form[key] = obj[key]
    }

Upvotes: 2

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

To make two-way binding between your input and store state you could use a writable computed property using set/get methods :

setup(){
  const store=useStore()

   const username=computed({
       get:()=>store.getters.getUsername,
       set:(newVal)=>store.dispatch('changeUsername',newVal)
    })

return {username}
}

template :

<input v-model="username" />

Upvotes: 2

Related Questions