3

I have a simple form asking for username and password. Those are my Vue.js data

  data: {
    app_images:[
      { app: '../assets/img/logos/logo.png' }
    ],
    json_repository:[],
    user: {
      username: null,
      password: null
    },
    submitted: null
  }

Username and password field in the form are bound to user.username and user.password. Pressing a sign in button execute doLogin function

methods: {
  doLogin: function() {
    this.submitted = this.user;
},

Problem is that from this moment on, every edit in the form also change the value in "submitted" field and i want to avoid that

2 Answers 2

14

You can create a copy of your data to avoid this issue.

methods: {
  doLogin: function() {
    this.submitted = Object.assign({}, this.user);
},

Now your this.submitted and this.user are no longer referring to the same object and changing one will not change the other.

Sign up to request clarification or add additional context in comments.

1 Comment

Fast as a rabbit and fixed my problem!
0

Object.assign({}, object) is not working properly when you have multiple inner objects. I solve this problem with store object before change as string with JSON.stringify and then rollback object with JSON.parse like...

this.beforeEditingCache = JSON.stringify(this.editObject);

and on cancel

this.editObject = JSON.stringify(this.beforeEditingCache);

you can use this in edit data in forms and rollback data if cancel the edit.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.