admin管理员组

文章数量:1287487

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

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

Share Improve this question edited Jun 8, 2017 at 13:33 Razinar asked May 12, 2017 at 14:06 RazinarRazinar 7673 gold badges13 silver badges24 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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.

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.

本文标签: javascriptAvoid databinding for a variable in VuejsStack Overflow