import{ax as i,z as a,A as n,b2 as l}from"./chunks/framework.DkLJC2NO.js";const E=JSON.parse('{"title":"storageService方法","description":"","frontmatter":{},"headers":[],"relativePath":"api/editor/storageServiceMethods.md","filePath":"api/editor/storageServiceMethods.md"}'),t={name:"api/editor/storageServiceMethods.md"};function e(p,s,h,k,r,g){return n(),a("div",null,[...s[0]||(s[0]=[l(`

storageService方法

getStorage

js
import { storageService } from '@tmagic/editor';

const storage = storageService.getStorage();
console.log(storage); // localStorage

// 通过插件替换为 sessionStorage
storageService.usePlugin({
  afterGetStorage() {
    return window.sessionStorage;
  },
});

getNamespace

js
import { storageService } from '@tmagic/editor';

const namespace = storageService.getNamespace();
console.log(namespace); // 'tmagic'

clear

js
import { storageService } from '@tmagic/editor';

storageService.clear();

getItem

js
import { storageService } from '@tmagic/editor';

// 获取字符串
const str = storageService.getItem('myKey');

// 使用自定义命名空间
const value = storageService.getItem('key', { namespace: 'custom' });

// 指定协议类型
const num = storageService.getItem('count', { protocol: Protocol.NUMBER });

key

js
import { storageService } from '@tmagic/editor';

const firstKey = storageService.key(0);
console.log(firstKey);

removeItem

js
import { storageService } from '@tmagic/editor';

// 移除默认命名空间下的存储项
storageService.removeItem('myKey');

// 移除自定义命名空间下的存储项
storageService.removeItem('key', { namespace: 'custom' });

setItem

js
import { storageService, Protocol } from '@tmagic/editor';

// 存储字符串
storageService.setItem('name', 'tmagic');

// 存储对象
storageService.setItem('config', { a: 1, b: 2 }, { protocol: Protocol.OBJECT });

// 存储数字
storageService.setItem('count', 100, { protocol: Protocol.NUMBER });

// 使用自定义命名空间
storageService.setItem('key', 'value', { namespace: 'custom' });

destroy

js
import { storageService } from '@tmagic/editor';

storageService.destroy();

use

使用中间件的方式扩展方法,上述方法中标记有扩展支持: 是的方法都支持使用use扩展

js
import { storageService } from '@tmagic/editor';

storageService.use({
  getItem(key, options, next) {
    console.log('获取存储项:', key);
    return next();
  },
});

usePlugin

相对于use, usePlugin支持更加灵活更加细致的扩展, 上述方法中标记有扩展支持: 是的方法都支持使用usePlugin扩展

每个支持扩展的方法都支持定制before、after两个hook来干预原有方法的行为,before可以用于修改传入参数,after可以用于修改返回的值

js
import { storageService } from '@tmagic/editor';

storageService.usePlugin({
  beforeSetItem(key, value, options) {
    console.log('设置前:', key, value);
    return [key, value, options];
  },
  
  afterGetItem(result, key, options) {
    console.log('获取后:', result);
    return result;
  },
});

removeAllPlugins

删掉当前设置的所有扩展

js
import { storageService } from '@tmagic/editor';

storageService.removeAllPlugins();
`,40)])])}const d=i(t,[["render",e]]);export{E as __pageData,d as default};