vue3:pinia+持久化使用

pinia中文文档:https://pinia.web3doc.top/

持久化插件:pinia-plugin-persist

用法如下:

1、在main.ts文件引入

import { createPinia } from 'pinia';
import piniaPersist from 'pinia-plugin-persist';

// pinia
const pinia = createPinia();
// pinia持久化存储插件
pinia.use(piniaPersist);

const app = createApp(App);
app.use(pinia);

2、新建store,在store文件里面配置

import { defineStore } from 'pinia';

export const useStore = defineStore('main', {
  // state
  state: () => {
    return {
      msg: ''
    }
  },

  // action
  actions: {

  },
  // 持久化存储
  persist: {
    enabled: true , // 这个配置代表存储生效,而且是整个store都存储
  },
});

3、tips:在外部js使用pinia,尽量避免全局使用,否则容易报以下错误
"getActivePinia was called with no active Pinia. Did you forget to install pinia?"

import { useStore } from '../store/index';

// 不推荐全局
// const store = useStore();

// 建议局部使用到的时候再创建调用
export function fn() {
	const store = useStore();
	console.log('store', store);
}

你可能感兴趣的:(Vue.js,javascript,前端)