Created
August 15, 2017 10:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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