A small Vue.js app
Saving to a local file
In the previous post, I added buttons to save and load an array of objects to and from localStorage
. While I may want my app to store something in localStorage
, I know I want to be able to save my entries to a file.
Goal
I want the click handler on the “Save tiddlers” button to invoke a method that downloads the tiddlers
array to a local file I can access easily through my computer’s filesystem.
There is a library, FileSaver.js
, which makes this easy to accomplish, and I’ll be using that.
The FileSaver.saveAs()
method takes as its first argument either a file, a URL, or a blob. Since I don’t have a file or a URL, I will use the Blob
constructor to make a blob from the data I want to save (which is, at the moment, the tiddlers
array).
Breakdown
- Link the
FileSaver.js
library with the others in the html file. - Write a
saveFile()
method. It will: - Create a
Blob
object for theFileSaver.saveAs()
method - Put together a filename
- Invoke
FileSaver.saveAs()
- Point the click handler on the “Save” button to the
saveFile()
method
1. Link to FileSaver.js
I’m linking to the minimized version. Again I’m using jsDelivr, but you could use another CDN or a local version on the server .
Here’s everything I’m linking to in the bottom of this post’s Markdown file (which Hugo turns into an HTML file):
<link rel="stylesheet" href="/css/minapp_v01.css">
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/moment@2.22.2/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/filesaver.js-npm@1.0.1/FileSaver.min.js"></script>
<script type="text/javascript" src="minapp_v16.js"></script>
2. Write the saveFile()
function
a. Prepare a Blob
to pass to FileSaver.saveAs()
Use the Blob()
constructor.
var blob = new Blob([JSON.stringify(this.tiddlers)], {type: "application/json"})
b. Assemble a filename
For now, I’ll use a timestamp prefixed with tiddlers_
.
var createdTime = moment().format('YYYYMMDDHHmmssZZ')
var fileName = 'tiddlers_' + createdTime + '.json'
c. Invoke FileSaver.saveAs()
saveAs(blob, fileName)
The final method:
saveFile() {
var blob = new Blob([JSON.stringify(this.tiddlers)], {type: "application/json"})
var createdTime = moment().format('YYYYMMDDHHmmss')
var fileName = 'tiddlers_' + createdTime + '.json'
saveAs(blob, fileName)
}
3. Hook up a click handler to invoke the new saveFile()
method
<button id="save-tiddlers" @click="saveFile">Save tiddlers to file</button>
The code at this point: minapp_v16.js