pinia是什么?
pinia是一个用于vue的状态管理库,类似于vuex,是vue的另一种状态管理工具
与vuex相比
与 Vuex 相比,Pinia 提供了一个更简单的 API,具有更少的规范,提供了 Composition-API 风格的 API,最重要的是,在与 TypeScript 一起使用时具有可靠的类型推断支持。
mutations 不再存在。
无需创建自定义复杂包装器来支持 TypeScript,所有内容都是类型化的,并且 API 的设计方式尽可能利用 TS 类型推断。
不再需要注入、导入函数、调用函数、享受自动完成功能!
无需动态添加 Store,默认情况下它们都是动态的
不再有 modules 的嵌套结构
- 列表项pinia中只有state、getter、action,抛弃了Vuex中的Mutation
- 列表项pinia中action支持同步和异步,Vuex不支持
- 列表项支持服务端渲染。
安装
npm install pinia
/src/store/modules/user.js
import { defineStore } from 'pinia'
//defineStore(name,options)
//name:一个字符串,必传项,该store的唯一id。
//options:一个对象,store的配置项,比如配置store内的数据,修改数据的方法等等。
const useAppStore = defineStore('user', {
state: () => ({
sidebar: {
hide: false
},
device: 'desktop'
}),
actions: {
toggleSideBar(withoutAnimation) {
this.sidebar.hide = 1
}
}
})
export default useAppStore
/src/store/index.js
import {
createPinia
} from 'pinia'
const store = createPinia()
export default store
main.js
import pinia from '@/store/index'
app.use(pinia).use(router).mount('#app')
其他组件使用
监听pinia数据
import useAppStore from '@/store/modules/user'
const sidebar = computed(() => useAppStore().sidebar)
使用数据
// 将pinia中的数据转为响应式
import { storeToRefs } from 'pinia';
import useAppStore from '@/store/modules/user'
const store = useAppStore();
const { sidebar, device } = storeToRefs(store);
//使用pinia的actions方法
sotre.toggleSideBar()