iT邦幫忙

2024 iThome 鐵人賽

DAY 13
0

最後讓我們來完成儲存的功能,基本上整個todolist就完成了,我們儲存的位置因為只有純前端,所以我們選擇存在locale storage,locale storage的儲存格式內容只能是字串,所以我們必須要用 JSON.stringify將我們的內容轉為字串化,首先讓我們再先前joinList這個function補上轉字串還有儲存的句子:

const joinList = () => {
	if (inputVal.value.trim() === '') {
		let message = '未輸入訊息';
		alert(message);
		console.log(toDoList.value.length);
		return;
	} else {
		let maxKey = 0;
		toDoList.value.forEach((item) => {
			if (item.key > maxKey) {
				maxKey = item.key;
			}
		});
		toDoList.value.unshift({
			name: inputVal.value.trim(),
			edit: false,
			key: maxKey + 1
		});
		toDoList.value.forEach((item, index) => {
			item.edit = false;
		});
		//補上下列兩句
		const toDoListString = JSON.stringify(toDoList.value);
		localStorage.setItem('toDoList', toDoListString);
		
		inputVal.value = '';
	}
};

上面兩句我們宣告了一個toDoListString 是我們將toDoList.value進行JSON.stringify轉為字串的結果,然後我們用localStorage.setItem的方式存了一個叫做’toDoList’的key,value則是轉完字串化的toDoListString。

而在刪除的部分我們也需要加入相關的句子進行刪除:

const deleteItem = (item) => {
	toDoList.value = toDoList.value.filter((e) => item.key !== e.key); //剔除掉item.key===index的物件,也就是自己
	//加上下面兩句
	const toDoListString = JSON.stringify(toDoList.value);
	localStorage.setItem('toDoList', toDoListString);
};

和上面新增一樣,當我們對toDoList.value有做改動的話,那麼我們都需要及時的更新toDoListString ,接下來是修改的function:

const edit = (item) => {
	if (item.edit) {
		if (item.name === '') {
			debugger
			let message = '修改失敗,內容不可為空';
			alert(message);
			//新寫一個getListk的function
			getList();
		} else {
			item.edit = false;
		}
	} else {
		toDoList.value.forEach((todo) => {
			todo.edit = false;
			//加上下面兩句
			const toDoListString = JSON.stringify(toDoList.value);
			localStorage.setItem('toDoList', toDoListString);
		});
		item.edit = true;
	}
};

我們在 edit 這個function除了else區塊加了寫入locale storage的部分以外,也在修改失敗的區塊加了一個叫做getList的function,這個function是用來做甚麼的呢?首先有儲存,就必然有讀取,我們已經完成了儲存的句子,那麼我們接下來就要來寫讀取的function,也就是這個getlist:

const getList = () => {
	const toDoListString = localStorage.getItem('toDoList');
	if (!toDoListString) {
		toDoList.value = [];
	} else {
		toDoList.value = JSON.parse(toDoListString);
	}
};
getList();

我們宣告了一個toDoListString 變數去尋找(getItem)我們的localStorage是否有toDoList這個key值的字串value,如果沒有(!toDoListString)的話我們便製造一個空陣列,如果有的話我們便將這個名為toDoList的字串用JSON.parse將她轉回原本的型態

https://ithelp.ithome.com.tw/upload/images/20240922/201691701B3dpVzdaK.png

打開開發者工具,看向應用程式的本機儲存空間(localStorage),我們可以看到現在甚麼都沒有,可以當我們新增一項事項之後:

https://ithelp.ithome.com.tw/upload/images/20240922/20169170wxCwcnvvXQ.png

這時候就可以看見我們新增了一個名為toDolist的內容,裡面便是我們剛剛所要儲存的資料了!

基本上到這邊一個簡單的代辦事項專案就已經完成摟~接下來的日子我們將給她加一些小小的額外功能讓我們的toDolist在稍微豐富一點~


上一篇
和2魚坐牢的第十二天-todolist之修改功能
下一篇
和2魚坐牢的第十四天-todolist之i18n多語系
系列文
和鱷魚組長的坐牢30天之vue的簡易todolist和Astro的簡易部落格實現17
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言