Before presenting an alternative to your case, it follows information that justifies the way I am going to do it.
Vuex has a setting called strict mode , which can be true
or false
, this setting with value false
allows you to make state
out of muntations
of store
. Read more about strict mode and why it is not recommended in production mode here >.
This is based on the documentation of vue, nuxt, my experience and some more links that I will leave below.
This method I use in a framework of the nuxt framework , I used as an example a state
of user with property to the name.
Based on the documentation of vue, vuex, my experience and some links that I will put below, basically input
receives the value of getter
and pressing enter will fire actions
as method that takes the field value and refresh user
object using spread operator to merge, in state
of store.
If you have any questions, please comment!
index.vue
<template>
<input type="text" :value="user.name" @keyup.enter="updateName($event)">
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
export default {
methods: {
...mapActions({
updateName: 'updateName'
})
},
computed: {
...mapGetters({
user: 'getUser'
})
}
}
</script>
store / index.js
import Vuex from 'vuex'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
const createStore = () => {
return new Vuex.Store({
state: {
user: {
name: ''
}
},
getters,
actions,
mutations
})
}
export default createStore
store / getters.js
const getters = {
getUser(state) {
return state.user
}
}
export default getters
store / actions.js
const actions = {
updateName({ commit, getters }, event) {
event.preventDefault()
let name = event.target.value
commit('SET_USER', { name })
}
}
export default actions
store / mutations.js
const mutations = {
SET_USER(state, user) {
state.user = { ...state.user, ...user }
}
}
export default mutations
links
Vuex Store for Nuxt.js documentation
Event when pressing enter on Vue.js