[Vuejs]-Vue 3 with Vuex 4

2👍

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" />

2👍

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]
    }
👤nahoj

Leave a comment