本文最后更新于 419 天前,其中的信息可能已经有所发展或是发生改变。
Pinia 使用
随着 Vue3 的逐步推广,状态管理可以利用响应式函数实现简单的 hook 管理全局变量。但是可以考虑使用一个更加简单的方法更高效、有序的管理,那就是 pinia。Vue 官方也将推荐状态管理库由 Vuex 更新为 Pinia
什么是 Pinia
Intuitive, type safe and flexible Store for Vue(直观、类型安全且灵活的 Vue 状态管理器)
与 Vuex 有什么区别
相同点
都是 Vue 的状态管理器
都是响应式的数据
都支持同步、异步修改数据
都是安全的数据管理器
不同点
pinia
更加轻量的状态管理器;更加简单的使用方式;更加直观的数据管理方式
没有 Mutations 概念,减少心智负担
纯 TypeScript 设计,完全满足 TypeScript 开发者的使用体验
支持多个 Store
vuex
支持调试功能,如时间旅行和编辑
为什么推荐使用 Pinia
简单的使用方式,是个人推荐的最大理由,话不多说上示例
安装 Pinia
yarn add pinia
# or with npm
npm install pinia
注册 Pinia
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
创建 Store(这里只举例:Setup Stores)
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const name = ref('Eduardo')
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, name, doubleCount, increment }
})
页面引入使用
import { useCounterStore } from '@/stores/counter'
export default {
setup() {
const store = useCounterStore()
return {
// you can return the whole store instance to use it in the template
store,
}
},
}
如何选择状态管理器
如果大家已经上手 vue3 了,个人建议直接在初始化工程时使用 pinia 。如果是 typescript 开发者,不想体验麻烦的 vuex 的类型问题,也可以直接选择体验一番。祝大家开发愉快