Local storage to store data using localStorage

New Project (do not know how new projects refer to the article:? Vue vue-CLI3 building project )

Directory Structure

Interface display


Add store.js

export default {
  fetch: (key) => JSON.parse(window.localStorage.getItem(key)),
  save: (data, key) => window.localStorage.setItem(key, JSON.stringify(data)),
};

The function of the two localStorage export operation out.
Need to import came when in use.

App.vue coding

html

<template>
	<div id="app">
		<div class="wrap">
			<input type="text" v-model="keyword" @keydown.enter="addData" />
			<ul v-if="list.length">
				<li
					v-for="(item, index) in list"
					:key="index"
					@click="changeState(index)"
					:class="{complete: item.state}"
				>{{ item.txt }}</li>
			</ul>
		</div>
	</div>
</template>

script

import store from "./common/store"; // store module incorporated 

const STORAGE_KEY = "My-Key"; 

Export {default 
	name: "App", 
	Data () { 
		return { 
			keyword: "", 
			List: store.fetch ? (STORAGE_KEY) store.fetch (STORAGE_KEY) : [], // data from a local store 
		}; 
	}, 
	Components: {}, 
	Mounted () {}, 
	Methods: { 
		// add data 
		the addData () { 
			the this. list.push ({ 
				TXT: this.keyword, 
				state: to false, 
			}); 
			this.keyword = ""; 
		}, 
		// after clicking change state 
		ChangeState (index) { 
			This.List [index] = .STATE the this!. List [index] .STATE; 
		}, 
	},
	watch: {
		// here monitor changes in the entire data list, each time to avoid the need to modify the data when they are stored locally 
		list: { 
			Handler () { 
				store.save (This.List, STORAGE_KEY); // written to the local memory 
			}, 
			Deep: after true, // switch to false, click on the toggle state, refresh to see results, not trigger watch. 
		} 
	} 
};

css

*{margin: 0;padding: 0;}
.wrap {width: 80%;margin: 0 auto;}
input {height: 30px;width: 100%;}
li {
	height: 30px;
	line-height: 30px;
	background: #e2e2e2;
	margin: 4px 0;
	cursor: pointer;
	list-style-type: none;
	padding: 0 10px;
}
li.complete {background: #5cce5c;color: #fff;}

Guess you like

Origin www.cnblogs.com/huipinpuzi/p/12168160.html