A small Vue.js app
Deleting objects with confirmation
Now my Vue app can add, edit, and list objects that I call “tiddlers” (after TiddlyWiki), but that you could think of as text notes. One thing that’s missing is the ability to get rid of them once created.
Goal
In this step I’ll add the ability to delete an object from the tiddlers
array. I’ll add a “Delete tiddler” button over the tiddler display area, and give it a listener for clicks, and a method that the listener invokes to delete objects, asking the user for confirmation.
Breakdown
- Add the button and give it an event listener
- Follow the same steps as in the
updateTiddler()
method to get the index of the target tiddler - Use
splice()
to remove the tiddler at that index fromtiddlers
- Add an
if
statement insideremoveTiddler()
to require a confirmation before deletion - Reset the UI and data
1. Add a “Delete tiddler” button with a listener
The @click
listener (short for v-on:click
) will invoke a method called removeTiddler()
:
<button id="delete-tiddler" @click="removeTiddler">Delete tiddler</button>
2. Get the index of the target tiddler
I can reuse the callback function isTheTiddler()
I wrote for the find()
in updateTiddler()
, since I’m doing exactly the same thing, except that when I get to the splice()
part, I’ll delete the object from the array without putting anything in its place.
Use find()
to get the object:
this.tiddlers.find(this.isTheTiddler)
.
Get that object’s index:
this.tiddlers.indexOf(tiddler)
.
3. Use splice()
to remove the tiddler at that index from tiddlers
This is simple with this.tiddlers.splice(idx, 1)
.
4. Add an if
statement to require a confirmation before deletion
I’m going to check two things before trying to delete a tiddler from the tiddlers
array: a) that currentTiddler
is a tiddler that exists in the array, as opposed to a new one that hasn’t been submitted yet, and which thus doesn’t exist to be deleted; and b) that the user meant to click the button.
For a), all I have to check is that the currentCreated
property, set by the selectTiddler()
method, is not undefined
.
For b), I’ll use the confirm()
method of the Window
object to pop up a modal dialog asking the user to click a button to confirm the action.
I can string both requirements into one line with a logical AND.
Now that I know how to insert a confirmation dialog, I can think about whether it’s really the best design decision to use it. It’s trivial to remove if I decide to.
5. Reset the UI and data
I already wrote a method, resetTiddler()
, to do this, in Breaking up some methods to tidy up, so my new method can just invoke this.
The finished method looks like this:
removeTiddler() {
if (this.currentCreated != undefined && confirm("Delete this tiddler?")) {
var tiddler = this.tiddlers.find(this.isTheTiddler)
var idx = this.tiddlers.indexOf(tiddler)
this.tiddlers.splice(idx, 1)
this.resetTiddler()
}
},
The code: minapp_v13.js