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" />
- [Vuejs]-Clear data object on route change
- [Vuejs]-Vue.js – why is my debounce function not working with arrow function
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]
}
Source:stackexchange.com