一、pinia
是什么:
- Pinia 是 Vue.js 的轻量级状态管理库,是vuex的升级版。
- pinia核心概念是 state、actions、getters、modules、plugins
二、pinia基本使用:
- 装包:npm i pinia。
- 在main.js中use
1 2 3 4 5 6 7 8
| import { createApp } from "vue" import App from "./App.vue" import { createPinia } from "pinia" const app = createApp(App) const pinia = createPinia() app.use(pinia).mount("#app")
|
- 定义模块:例如 新建文件src/store/xxxx.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import { defineStore } from 'pinia' import { ref } from 'vue'
export default defineStore('counter',() => { const count = ref(0) const addCount = () => { count.value++ } const doubleCount = computed(() => { return count.value * 2 }) return { count, addCount, doubleCount } })
|
- 使用
1 2 3 4 5 6 7 8 9 10 11 12
| <template> <div> 首页{{ countStore.count }} </div> <button @click="countStore.addCount">dtn</button> </template> <script setup> import useCountStore from '../store/counter' const countStore = useCountStore() console.log(countStore) </script>
|
- 解构导入的 countStore,方法不能解构 (看个人需求解构)
1 2 3 4 5
| impor { storeToRefs } from 'pinia'
const { count, doubleCount } = storeToRefs(countStore)
|
三、持久化:
第三方插件
pinia-plugin-persistedstate
- 安装:npm i pinia-plugin-persistedstate
- 在main.js中导入
1 2 3 4 5 6
| import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(piniaPluginPersist) createApp(App).use(pinia).use(router).mount('#app')
|
- 使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import { defineStore } from 'pinia' import { computed, ref } from 'vue'
export default defineStore('counter',() => { const count = ref(0) const addCount = () => { count.value++ } const doubleCount = computed(() => { return count.value * 2 }) return { count, addCount, doubleCount } },{ persist:{ key:'counter', storage:sessionStorage, paths: ['count', 'xxxx'], } })
|