Home > Article > Web Front-end > Detailed example of using localstorage to store page information in Vue
This article mainly introduces the use of localstorage in vue to store page information. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Environment setup:
Reference: vue API
Super simple Vue.js environment setup tutorial
Details :
npm install --global vue-cli
## vue init webpack vue-project
cd vue-project
npm run dev
But we finally have to achieve:
How to achieve the effect as shown in the picture? 1. Modify App.vue to:
<template> <p id="app"> <p class='vue-demo'> <input type="text" class="txt" v-model='newItem' @keyup.enter='addItemFun'> <ul> <li v-for="its in items">{{its.name}}</li> </ul> </p> </p> </template> <script> import store from './store' export default { name: 'app', data() { return { newItem: '', items: store.fetch() } }, watch: { items: { handler: function(val, oldVal) { store.save(val); }, deep: true } }, methods: { addItemFun() { var _this = this; _this.items.push({ 'name': _this.newItem }); _this.newItem = ''; } } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } .vue-demo { width: 400px; margin: 0 30px; } .txt { width: 200px; height: 25px; line-height: 24px; border-radius: 5px; } </style>For those who are new to vue, they may not be familiar with watch, so please move to vue API or refer to Xiaoying Previously written article: vue - instance method/data2. In the same directory as App.vue, create a new store.js file:
const STORAGE_KEY = 'todos-vuejs' export default { fetch: function() { return window.JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '[]') }, save: function(items) { window.localStorage.setItem(STORAGE_KEY, window.JSON.stringify(items)) } }3. Open cmd in the project Window, run: npm run dev, it’s done. Related recommendations:
Detailed explanation of cookies to solve the problem that WeChat cannot store localStorage
Summary of HTML5 localStorage knowledge points
Use localStorage in HTML5 to implement the password remembering function
The above is the detailed content of Detailed example of using localstorage to store page information in Vue. For more information, please follow other related articles on the PHP Chinese website!