本地存儲 使用localStorage 存儲數據


新建項目(不知道怎么新建項目?參考文章:vue-cli3 搭建vue項目

目錄結構

界面顯示


添加store.js

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

將兩個操作localStorage的函數export出去。
需要在使用的時候import進來。

App.vue代碼編寫

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模塊

const STORAGE_KEY = "my-key";

export default {
	name: "app",
	data() {
		return {
			keyword: "",
			list: store.fetch(STORAGE_KEY) ? store.fetch(STORAGE_KEY) : [], // 從本地存儲中獲取數據
		};
	},
	components: {},
	mounted() {},
	methods: {
		// 添加數據
		addData() {
			this.list.push({
				txt: this.keyword,
				state: false,
			});
			this.keyword = "";
		},
		// 點擊后改變狀態
		changeState(index) {
			this.list[index].state = !this.list[index].state;
		},
	},
	watch: {
		// 這里監聽整個list數據的變化,避免每次修改數據的時候都需要進行本地存儲
		list: {
			handler() {
				store.save(this.list, STORAGE_KEY); // 寫入本地存儲
			},
			deep: true, // 切換為false之后,點擊切換狀態,刷新看效果,未觸發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;}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM