Skip to content

Instantly share code, notes, and snippets.

@lukasvermeer
Created August 15, 2017 10:09
Show Gist options
  • Save lukasvermeer/aa971aee822c65579b03663da8b3cafe to your computer and use it in GitHub Desktop.
Save lukasvermeer/aa971aee822c65579b03663da8b3cafe to your computer and use it in GitHub Desktop.
Using browser local storage to store form values for dynamic form using Vue.
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<form id="app">
<button v-if="hasStoredState()" @click.prevent="load">Load draft!</button>
<button v-if="hasStoredState()" @click.prevent="clear">Delete draft!</button>
<p>Count of text items: <input v-model="form.count" type="number"></p>
<p v-for="index in parseInt(form.count)">
Text {{index}}: <input v-model="form.text[index-1]">
</p>
</form>
<script>
var app = new Vue({
el: '#app',
data: {
form: {
count: 3,
text: ['one', 'two', 'three']
},
hasStoredState: function() { return localStorage.getItem('storedForm') ? true : false; }
},
methods: {
load: function() {
if (localStorage.getItem('storedForm')) {
this.form = JSON.parse(localStorage.getItem('storedForm'));
}
},
clear: function() {
localStorage.removeItem('storedForm');
}
},
watch: {
form: {
deep: true,
handler: function(f) {
localStorage.setItem('storedForm', JSON.stringify(f)) == '';
}
}
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment