Skip to content

多个标签页之间数据同步

使用 pinia-shared-state 来实现。

sh
pnpm install pinia pinia-shared-state
  • main.ts
js
// main.ts
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import { PiniaSharedState } from 'pinia-shared-state';
 
const app = createApp(App);
 
const pinia = createPinia();
app.use(pinia);
 
app.use(PiniaSharedState({
  enable: true,
  initialize: false,
  type: 'localstorage',
}));
 
app.mount('#app');
  • src/stores/counter.ts
ts
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useCounterStore = defineStore(
  'counter',
  () => {
    const count = ref(0)
    const doubleCount = computed(() => count.value * 2)
    function increment() {
      count.value++
    }
    return { count, doubleCount, increment }
  },
  {
    share: {
      // An array of fields that the plugin will ignore.
      omit: ['count'],
      // Override global config for this store.
      enable: true,
      initialize: true,
    },
  },
)