Editing a form with save and cancel options

后端 未结 1 436
陌清茗
陌清茗 2020-12-31 07:51

I\'m new to VueJS. I\'m trying to create a form with simple Save and Cancel functionality. When binding the model to form fields they get updated immediately as the inputs a

1条回答
  •  -上瘾入骨i
    2020-12-31 08:02

    There's a few ways to handle this. You could create a separate component for the form, pass props to it, and then handle the editing/saving by emitting changes or if you want to keep it in a single component you could use value binding and refs, e.g.

    var app = new Vue({
      el: '#app',
      data: {
        isEditing: false,
        user: {
          firstName: 'John',
          lastName: 'Smith'
        }
      },
      methods: {
        save() {
          this.user.firstName = this.$refs['first_name'].value;
          this.user.lastName = this.$refs['last_name'].value;
          this.isEditing = !this.isEditing;
        }
      }
    })
    .view {
      border-color: transparent;
      background-color: initial;
      color: initial
    }
    
    
    
    First Name:
    Last Name:

    Or you could use a variable cache mechanism (with suggested edits) e.g.

    var app = new Vue({
      el: '#app',
      data: {
        isEditing: false,
        user: {
          firstName: 'John',
          lastName: 'Smith',
        }
      },
      mounted() {
        this.cachedUser = Object.assign({}, this.user);
      },
      methods: {
        save() {
          this.cachedUser = Object.assign({}, this.user);
          this.isEditing = false;
        },
        cancel() {
          this.user = Object.assign({}, this.cachedUser);
          this.isEditing = false;
        }
      }
    })
    .view {
      border-color: transparent;
      background-color: initial;
      color: initial
    }
    
    
    First Name:
    Last Name:

    With any of these options you can set a status message at the start of the save method and then update it whenever you're done with the server call.

    0 讨论(0)
提交回复
热议问题