使用 vue 的离子存储

Ionic-storage with vue

我正在使用 Ionic Framework v5Vue 3.0.0 构建应用程序。

我使用 Vuex store 来存储全局应用程序信息,例如用户登录令牌。

// file src\store.ts
export const store = createStore({
    state(){
      return { 
        loginToken;
      }
    },
    mutations: {
      updateLoginToken(state: any, token: string){
        state.loginToken = token;
      }
    },
    getters: {
      token(state: any){
        return state.loginToken;
      }
    }
})

我还需要在关闭或刷新应用程序时保存此令牌,因此我需要将其存储在某种本地存储中。

官方文档建议使用@ionic/storage访问多个平台上的存储引擎。

要初始化商店,我需要执行以下代码:

import { Storage } from '@ionic/storage';

const storage = new Storage();
await storage.create();

我对这一切还很陌生,我找不到在哪里放置这段代码来初始化存储,以及我如何才能访问 vuex 存储中的存储对象,以执行 storage.set(...)storage.get(...)?

@ionic/storage 对比@capacitor/storage

首先你需要验证,如果你真的需要@ionic/storage,或者@capacitor/storage是否足够(大多数情况下是)。使用 @ionic/storage 需要在整个应用程序中共享一个实例。 @capacitor/storage 可以通过导入直接使用。

可以在此处找到这些插件之间的比较:

在这个答案中,我假设你真的想使用 @ionic/storage 所以你需要先创建一个实例,我们想分享它。

用于在您的应用程序中共享@ionic/storage 实例的插件

创建一个 vue 插件,在其中创建存储实例并将其保存在全局变量中。如果需要,还可以将其附加到您的 VUEX 商店。

在您的 main.js 中的某处,您将插件附加到您的 Vue 应用程序:

app
  .use(...)
  .use(yourPlugin)

插件代码:

import { Storage } from '@ionic/storage'

install: async (app) => {
  const storage = new Storage()
  const storageInstance = await storage.create()

  app.config.globalProperties.$ionicStorage = storageInstance
  app.config.globalProperties.$store.$ionicStorage = storageInstance // This one is only needed if you want to access the ionic storage instance in your VUEX store actions
}

将数据写入设备存储

在您的情况下,如果发生特定的 VUEX 突变,您希望向设备存储写入一些内容。在这种情况下,有多个选项可以写入设备存储。

或者你 运行 像这样在 VUEX 操作中进行突变,然后将其保存到设备存储中:

actions: {
  async setLoginToken ({ commit, state }, loginToken) {
    commit('updateLoginToken', loginToken)
    this.$ionicStorage.set({
      key: 'your-storage-key',
      value: JSON.stringify({ loginToken })
    })
  }
}

如果您只想同步几个 VUEX 存储属性,这种方法很有意义。如果你想同步所有东西,或者想让东西更加分离,你可以将 VUEX 插件附加到你的 VUEX 商店并订阅 mutations。

如何附加VUEX插件: https://vuex.vuejs.org/guide/plugins.html

一般来说,向您的商店注册一个 VUEX 插件允许您订阅 mutations。在您的情况下,每次更新登录令牌时 updateLoginToken 突变 运行s。所以插件需要注意在突变后将新的 loginToken 写入设备存储 运行.

这看起来类似于:

const myPlugin = store => {
  // called when the store is initialized
  store.subscribe((mutation, state) => {
    // called after every mutation.
    // The mutation comes in the format of `{ type, payload }`.
    // Make sure the code runs only for the relevant mutation

    store.$ionicStorage.set({
      key: 'your-storage-key',
      value: JSON.stringify(xxx)
    })
  })
}

从设备存储读取数据

现在您在设备存储中有了登录令牌。当应用程序重新启动时,您需要从那里获取它并将其推送到 VUEX 商店。有不同的方法来设置它。我个人更喜欢在自定义 Vue 插件中加载它。

首先,您再次将插件附加到您的 vue 应用程序。确保这个插件附加在上面的插件之后(全局共享 ionicStorage 实例的插件)。

在插件中,您只需从设备存储中读取保存的值并将其写入您的 VUEX 存储。

export default {
  install: async (app) => {
    const storageContent = await app.config.globalProperties.$ionicStorage.get({ key: 'your-storage-key' })
    const storageContentParsed = JSON.parse(storageContent.value || '{}')
    const $store = app.config.globalProperties.$store

    $store.replaceState({
      ...$store.state,
      ...storageData
    })
  }
}

注意:这些只是最少的代码片段。因此,请确保使其适应您自己的用例。一般来说,这应该确保 loginToken 正确同步到您的设备存储(在移动和网络上)。

我为使这一切正常工作所做的工作:

我创建了一个名为 Storage.ts 的插件文件,用于创建插件实例并将其添加到应用程序全局属性中:

import { Storage } from '@ionic/storage'

export default async function storageFactory(wsBaseUrl: string) {

  const storage = new Storage();
  // create storage
  const storageInstance = await storage.create();

  // my custom stuff here ...

  // in the end, return the plugin installer
  return {
    install(app: any){
      app.config.globalProperties.$ionicStorage = storageInstance;
      // special copy for vuex storage
      app.config.globalProperties.$store.$ionicStorage = storageInstance; 
    }
  }
}

然后在 main.ts 中,我将我的自定义插件添加到主应用程序中:

import storageFactory from '@/plugins/Storage';

// create storage plugin 
const storagePlugin = await storageFactory(config.wsBaseUrl);

// create app
const app = createApp(App)
  // ... other stuff here
  .use(storagePlugin)

// mount when router is ready
router.isReady().then(() => {
  app.mount('#app');
});

然后,在其他应用程序文件的任何地方,我都使用这样的存储空间:

// set new key
await (this as any).$ionicStorage.set('token', token );
// remove the key
await (this as any).$ionicStorage.remove('token');