Click-to-Edit text field with Vue

Viewed 25674

I am working on Vue js and having an issue editing a field. When I click on a field to edit it, all the editable fields become active. Here is my code.

 export default {
        props: ['profileHeight'],

        data() {
            return {
                User: User,
                isEditing: false,
                form:{
                    name:'',
                    email: '',
                },
            };
        },

        mounted() {
        },

        methods: {
            activateInEditMode() {
                this.isEditing = true
            },
            deActivateInEditMode() {
                this.isEditing = false
            }
        }
    }
 <span>Profile settings</span>
                        <p>Full name<span v-on:click="activateInEditMode" v-show="!isEditing">{{User.state.auth.name}}</span>
                            <span v-show="isEditing" >
                             <input v-model="form.name" type="text" class="form-control" >
                            </span>
                        </p>

                        <p>E-mail<span>{{User.state.auth.email}}</span>
                            <span v-show="isEditing" >
                             <input v-model="form.email" type="text" class="form-control" >
                            </span>
                        </p>

enter image description here

3 Answers

I have written a component for this, I call it Click-to-Edit.

What it does:

  • Supports v-model
  • Saves changes on clicking elsewhere and on pressing Enter

ClickToEdit.vue:

<template>
  <div>
    <input type="text"
           v-if="edit"
           :value="valueLocal"
           @blur.native="valueLocal = $event.target.value; edit = false; $emit('input', valueLocal);"
           @keyup.enter.native="valueLocal = $event.target.value; edit = false; $emit('input', valueLocal);"
           v-focus=""
             />
        <p v-else="" @click="edit = true;">
          {{valueLocal}}
        </p>
    </div>
</template>

<script>
  export default {

  props: ['value'],

  data () {
  return {
      edit: false,
      valueLocal: this.value
    }
  },

  watch: {
    value: function() {
      this.valueLocal = this.value;
    }
  },

  directives: {
    focus: {
      inserted (el) {
        el.focus()
      }
    }
  }

}
</script>
Related