本地存储 使用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。
		},
	},
};

style

*{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;}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值