Answers for "update a single field in array in mutation vuejs"

1

update a single field in array in mutation vuejs

// store/index.js

export default createStore({
  state: {
    users: [
      {
        id: 1,
        name: 'Israel',
        country: 'nigeria',
        state: 'lagos',
        gender: 'male',
        active: false,
        next_of_kin: {
          name: 'Oyin',
          gender: 'female',
          location: 'Lagos, Nigeria'
        }
      },
      {
        id: 2,
        name: 'Elizabeth',
        country: 'nigeria',
        state: 'lagos',
        gender: 'female',
        active: true,
        next_of_kin: {
          name: 'Debbie',
          gender: 'female',
          location: 'Lagos, Nigeria'
        }
      }
    ]
  },

  mutations: {
    changeData (state, payload) {
      const user = state.users.find(user => user.id === payload.id)
      user.name = payload.name
      user.active = payload.active
    }
  }

})

// in your view (Home.Vue)
// you can use a computed property or write it in a method,
// in my case, I wrote it in a method so the function is called on a 
// button click

methods: {
    changeName () {
      const payload = {
        id: 1,
        name: 'tope',
        active: true
      }
      this.$store.commit('changeData', payload)
    }
}

// Chat me on whatsapp for more tips on Vue and Django.
// +2348137933308
Posted by: Guest on May-29-2021

Code answers related to "update a single field in array in mutation vuejs"

Browse Popular Code Answers by Language