I am using vue-multiselect and I would like to store and later load selected values using localStorage. Storing data is quite OK for me, but I struggle with loading data back into the select component.
I was able to acomplish this task within one file, but in order to improve project readability, I have separated multiselect definitions into another file. Although it has improved the readability, but all other things get worse.
Please note, that there are more multiselects and more fields under formData.
Vue 3.xvue-multiselect 3.0.0-beta.3
func.js
import formData from './formData.js'
import VueMultiselect from 'vue-multiselect'
export const TimeframeDropdown = {
data() {
return {
selected: ["5m"],
timeframes: ["5m", "15m"]
};
},
watch: {
selected(newVal) {
formData.multiselect_input = newVal;
}
},
render() {
return (
<VueMultiselect
v-model={this.selected}
options={this.timeframes}
multiple={true}
/>
);
},
};
//There are more dropdowns in my code
...
formData.js
export default {
multiselect_input: '',
another_multiselect_input: '',
yet_another_multiselect_input: ''
//...
}
//There are more options in my code
page.vue
<TimeframeDropdown />
<AnotherDropdown />
<YetAnotherDropdown />
<button @click="store">store</button>
<button @click="load">load</button>
<script>
import * as t from './func.js'
import formData from './formData.js'
export default {
components: {
...t,
},
data() {
return {
formData: formData
}
},
methods: {
store() {
localStorage.setItem('test_key', JSON.stringify(this.formData.multiselect_input));
},
load() {
const savedData = localStorage.getItem('test_key');
this.formData = JSON.parse(savedData);
},
}
</script>
