鸿蒙开发-使用Storage实现数据存储
場景
鴻蒙開發-從搭建todolist待辦事項來學習組件與js之間的交互:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/118384865
在上面實現一個簡單的todolist之后,待辦事項的數據并沒有進行存儲。
每次進入頁面就會重新加載數據源的數據。
所以怎樣將數據存儲。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
參照官方的API文檔,需要導入模塊
import storage from '@system.storage';讀取存儲的內容
storage.get(OBJECT)參數
| key | string | 是 | 內容索引。 |
| default | string | 否 | key不存在則返回的默認值。如果未指定,則返回空字符串,長度為0。 |
| success | Function | 否 | 接口調用成功的回調函數,返回存儲的內容。 |
| fail | Function | 否 | 接口調用失敗的回調函數。 |
| complete | Function | 否 | 接口調用結束的回調函數。 |
示例
storage.get({key: 'storage_key',success: function(data) {console.log('call storage.get success: ' + data);},fail: function(data, code) {console.log('call storage.get fail, code: ' + code + ', data: ' + data);},complete: function() {console.log('call complete');}, });修改存儲的內容
參數
| key | string | 是 | 要修改的存儲內容的索引。 |
| value | string | 否 | 新值。value是長度為0的空字符串,則刪除索引為key的數據項。 |
| success | Function | 否 | 接口調用成功的回調函數。 |
| fail | Function | 否 | 接口調用失敗的回調函數。 |
| complete | Function | 否 | 接口調用結束的回調函數。 |
示例
storage.set({key: 'storage_key',value: 'storage value',success: function() {console.log('call storage.set success.');},fail: function(data, code) {console.log('call storage.set fail, code: ' + code + ', data: ' + data);}, });通過key來進行讀取和存儲。
所以在上面todolist的js中導入模塊后,添加生命周期方法onInit,
在初始化完成后從storage中讀取數據并賦值給todolist
??? onInit() {storage.get({key: 'todoList',success: data => {console.log('獲取Storage成功' + data);this.todoList = JSON.parse(data)}});},然后再新建一個存儲數據的方法
??? setStorage() {storage.set({key: 'todoList',value: JSON.stringify(this.todoList)});},在對todolist進行增刪改時調用存儲的方法
??? remove(index){console.log(index)this.todoList.splice(index,1)this.setStorage();},addTodo() {this.todoList.push({info:this.inputTodo,status: false})this.setStorage();},checkStatus(index){console.log(index);this.todoList[index].status = !this.todoList[index].status;this.setStorage();},完整的js代碼
import todoList from "../../common/datas/todoList.js" import router from '@system.router'; import storage from '@system.storage'; export default {data: {// 待辦事件列表todoList,inputTodo: "IDE無法調用輸入"},onInit() {storage.get({key: 'todoList',success: data => {console.log('獲取Storage成功' + data);this.todoList = JSON.parse(data)}});},setStorage() {storage.set({key: 'todoList',value: JSON.stringify(this.todoList)});},computed:{needTodoNum(){let num = 0;this.todoList.forEach(item => {if(!item.status){num++;}});return num;}},remove(index){console.log(index)this.todoList.splice(index,1)this.setStorage();},addTodo() {this.todoList.push({info:this.inputTodo,status: false})this.setStorage();},checkStatus(index){console.log(index);this.todoList[index].status = !this.todoList[index].status;this.setStorage();},getNewTodo(e){this.inputTodo = e.value;},goback(){router.back();} }運行效果
總結
以上是生活随笔為你收集整理的鸿蒙开发-使用Storage实现数据存储的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 鸿蒙开发-从搭建todolist待办事项
- 下一篇: 鸿蒙开发-使用fetch发起网络请求