Max
Max

Reputation: 55

Am I accessing the DOM correctly in Vue.js?

Am I accessing the DOM correctly in Vue.js? My task is such that when I click on the title, a form appears and I can edit the record in it. To cancel, press ESC, and to save, press ENTER.

my template:

<div v-for="(note, i) in notes" :key="i">
    <div class="card-body">
        <h5 class="card-title" @click="editNote($event, i)">{{note.title}}</h5>
        <input type="hidden">
    </div>
</div>

my script:

editNote (event, i){
    let parent = event.target,
        block = parent.closest('.card-body'),
        input = block.querySelector('input'),
        text = parent.textContent;
    input.type = "text"
    input.value = text
    parent.style.display = "none"
    input.onkeydown = (e) =>{
        if (e.keyCode == 27){
            input.type = "hidden"
            parent.style.display = "block"
        }
        else if (e.keyCode == 13){
            input.type = "hidden"
            parent.style.display = "block"
            parent.textContent = input.value
            this.notes[i].title = input.value
        }
    }
}

Upvotes: 0

Views: 49

Answers (1)

FloWy
FloWy

Reputation: 984

Your solution is a solution, but you can do much better by using v-if, v-model and @keypress.

With v-if you can check whether a specific variable is true or not. With that you can manipulate your h5 and input by setting the variable in editNote to true. This is how you can get rid of the display CSS manipulation.

With @keypress in the input tag, you can get rid of the keydown event and enter your solution there.

With the v-model you can easily get the value whenever someone enters something in the input. Also, you can get directly the value of the input.

Checkout these links for more:

v-model

v-if

event handling

Upvotes: 2

Related Questions