You can use localStorage directly in Vue projects, because localStorage is part of the Web Storage API provided by the browser and is independent of the JavaScript framework, so it can be used anywhere in the Vue project, including component templates and script tags, and is applicable to both Vue 2 and Vue 3. The following describes the method of using localStorage in Vue 2 and Vue 3 respectively.
Using localStorage in Vue 2
Save data to localStorage
<template> <div> <button @click="saveData">Save the data to localStorage</button> </div> </template> <script> export default { methods: { saveData() { const data = { message: 'This is the data to be saved' }; // Convert object to JSON string const jsonData = (data); // Save to localStorage ('myData', jsonData); ('Data has been saved to localStorage'); } } }; </script>
Read data from localStorage
<template> <div> <button @click="getData">from localStorage Read data</button> <p v-if="data">Read data: {{ }}</p> </div> </template> <script> export default { data() { return { data: null }; }, methods: { getData() { // Read data from localStorage const jsonData = ('myData'); if (jsonData) { // Convert JSON string to object = (jsonData); ('Reading data from localStorage:', ); } else { ('No corresponding data was found in localStorage'); } } } }; </script>
Delete data in localStorage
<template> <div> <button @click="removeData">delete localStorage Data in</button> </div> </template> <script> export default { methods: { removeData() { // Delete the specified data in localStorage ('myData'); ('Data in localStorage has been deleted'); } } }; </script>
Using localStorage in Vue 3
Save data to localStorage
<template> <div> <button @click="saveData">Save the data to localStorage</button> </div> </template> <script setup> import { ref } from 'vue'; const saveData = () => { const data = { message: 'This is the data to be saved' }; const jsonData = (data); ('myData', jsonData); ('Data has been saved to localStorage'); }; </script>
Delete data in localStorage
<template> <div> <button @click="removeData">delete localStorage Data in</button> </div> </template> <script setup> const removeData = () => { ('myData'); ('Data in localStorage has been deleted'); }; </script>
Things to note
localStorage can only store data of string type, so when saving an object or array, you need to use the () method to convert it to a JSON string first, and then use the () method to convert it back to an object or array when reading.
The data stored in localStorage will remain in the browser unless manually deleted, and the storage size is usually limited to around 5MB.
When using localStorage, pay attention to the security of data and avoid storing sensitive information
This is the end of this article about whether localStorage can be used directly in vue. For more related vue localStorage content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!