0
votes

I use django-rest-framework + vue.js

My goal is to make a Form to edit user-profile.

Here is what i have:

<input type="email" v-model="userEdit.email">
<input type="text" v-model="userEdit.location">
<input type="text" v-model="userEdit.bio">

my inputs are bounded to data object "editUser"

data() {
  return {
    'editUser': {
      email: '',
      location: '',
      bio: '',
      image: '',
    },
  }
},

so now i can send this object to the server and change user-profile information.

sendChanges() {
  const fd = new FormData();
  fd.append('image', this.editUser.image, this.editUser.image.name)
  fd.append('email', this.editUser.email)
  fd.append('location', this.editUser.location)
  fd.append('bio', this.editUser.bio)
  this.axios.put(userDetailURL + this.routeUser, fd)
    .then(response => {
      console.log(response)
    })
    .catch(error => {
      console.log(error.response)
    })
},

this form works and updates info, but there is a thing i dont like:

The input fields are always empty, and user needs to fill all of them before can press save button.

even if the user wants to change only "location" he must fill other inputs which are empty.

adding dynamic :value="userDetail.email" to the input -- no work.

is there any other way to add current value to input field and still have v-model? current data is here:

computed: {
      userDetail() {
        return this.$store.getters.userDetail;
      },
    },
1
What do you mean? You are using empty strings '' for your inputs. Pass default values here.Ohgodwhy
"my inputs are bounded to data object "editUser"" <- no they're not, they're bound to userEditPhil
"is there any other way to add current value to input field and still have v-model?" <- yes, assign the appropriate data to your data properties. We don't know when or where this "current data" comes from so cannot help any furtherPhil
Have you read the guide? vuex.vuejs.org/guide/forms.htmlPhil
@mutaputa feel free to answer your own question then. There will be other people who run into this same problem in the futurePhil

1 Answers

0
votes

The problem is that you are binding the values in data to the form and those values are initially empty.

The cleanest and easiest solution I can think of right now is updating the initial data in mounted lifecycle hook:

mounted () {
  // Use Object.clone to prevent modifying the userDetail object directly
  this.editUser = Object.clone(this.$store.getters.userDetail)
}

There are other solutions, though. You could use a computed setter whose getter defaults to whatever is in the store but can be overridden when set.