继续自学中,最近在用 ts 重构先前写的 vue3 移动端模版,想着学着用一下 pinia。用完发现真香真不戳👍
pinia 的特点
- 支持 vue2 和 vue3,两者都可以使用 pinia;
- 语法简洁,支持 vue3 中 setup 的写法,不必像 vuex 那样定义 state、mutations、actions、getters 等,可以按照 setup Composition API 的方式返回状态和改变状态的方法,实现代码的扁平化;
- 支持 vuex 中 state、actions、getters 形式的写法,丢弃了 mutations,开发时候不用根据同步异步来决定使用 mutations 或 actions,pinia 中只有 actions;
- 对 TypeScript 支持非常友好。
pinia 的安装与使用
npm install pinia
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
// 引入 pinia
import { createPinia } from 'pinia'
const app = createApp(App)
const pinia = createPinia()
app
.use(pinia)
.mount('#app')
在 src/store
下新建 test.ts
import { ref } from 'vue'
import { defineStore } from 'pinia'
export const testStore = defineStore('test', () => {
const count = ref(0)
const update = () => count.value++
const setCount = (val: number) => {
count.value = val
}
return { count, update, setCount }
})
在使用的页面中import,就可以获取到 testStore实例
了
import { testStore } from '@/store/test'
const store = testStore()
数据的持久化
跟 vuex 一样,刷新后数据会丢失,为了解决这个问题,可以使用 pinia-plugin-persistedstate
这个插件
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
// 引入 pinia
import { createPinia } from 'pinia'
// 引入 pinia 数据持久化插件
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const app = createApp(App)
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
app
.use(pinia)
.mount('#app')
加上 persist: true
即可解决问题 🎉
// test.ts
import { ref } from 'vue'
import { defineStore } from 'pinia'
export const testStore = defineStore('test', () => {
const count = ref(0)
const update = () => count.value++
const setCount = (val: number) => {
count.value = val
}
return { count, update, setCount }
}, {
persist: true
})