M
M
myskypesla2018-08-08 14:58:58
Vue.js
myskypesla, 2018-08-08 14:58:58

How to use in v-model the properties of an object that is the value of a computed property?

there is an object in store.js

user: {
  firstName: '',
  lastName: '',
  age: '',
}


and there is a component

<template>
  form
    input(type='text', placeholder='firstName')
    input(type='text', placeholder='lastName')
    input(type='text', placeholder='age')
</template>


how to use computed as well as get and set in it to pass the value to store.js so that it looks something like this

<template>
  form
    input(type='text', placeholder='firstName', v-model='user.firstName')
    input(type='text', placeholder='lastName', v-model='user.lastName')
    input(type='text', placeholder='age', v-model='user.age')
</template>

<script>
export default {
  computed: {
    user: {
      get() {
        return this.$store.state.user;
      },
      set(value) {
        this.$store.commit('saveUser', value);
      },
    }
  },
};
</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-06-03
@myskypesla

The computed property will be an object from the state, wrapped in a Proxy to intercept the setting of property values ​​and cause a mutation:

user() {
  return new Proxy(this.$store.state.user, {
    set: (target, prop, value) => {
      this.$store.commit('updateUser', { [prop]: value });
      return true;
    },
  });
},

Accordingly, the mutation itself:
updateUser(state, payload) {
  Object.assign(state.user, payload);
},

https://jsfiddle.net/jgv3h15k/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question