一、安装
安装依赖包
npm install pinia -S
二、引入
在main.js实例化
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const store = createPinia()
const app = createApp(App)
app.use(store)
app.mount('#app')
三、定义 Store
src/stores/i18n.js
Option Store风格
import { defineStore } from 'pinia';
export const useI18nStore = defineStore('i18n', {
state: () => ({ lang: 'zh' }),
getters: {
langUpperCase: (state) => state.lang.toUpperCase(),
},
actions: {
langUpdate(val = 'zh') {
this.lang = val;
},
},
})
Setup Store风格
import { ref, computed } from 'vue';
import { defineStore } from 'pinia';
export const useI18nStore = defineStore('i18n', () => {
const lang = ref('lang');
const langUpperCase = computed(() => {
return lang.value.toUpperCase();
});
function langUpdate(val = 'zh') {
lang.value = val;
}
return {
lang,
langUpperCase,
langUpdate,
};
});
四、使用 Store
<script setup>
import { storeToRefs } from 'pinia'
import { useI18nStore } from '@/stores/i18n'
const store = useI18nStore();
const { lang, langUpperCase } = storeToRefs(store);
const { langUpdate } = store();
</script>
五、持久化
1.安装依赖
npm install pinia-plugin-persistedstate -S
2.将插件添加到 pinia 实例上 src/stores/index
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const store = createPinia()
store.use(piniaPluginPersistedstate)
export default store
3.作用到app上 main.js
import { createApp } from 'vue'
import App from './App.vue'
import store from '@/stores/index'
const app = createApp(App)
app.use(store)
app.mount('#app')
4.用法 创建 Store 时,将 persist 选项设置为 true。
import { defineStore } from 'pinia'
export const useStore = defineStore(
'main', () => {
const someState = ref('你好 pinia')
return { someState }
},
{
persist: true,
},
)