Pinia 是 Vue 的专属状态管理库,它允许你跨组件或页面共享状态。与 Vuex 相比,Pinia 不仅提供了一个更简单的 API,也提供了符合组合式 API 风格的 API,最重要的是,搭配 TypeScript 一起使用时有非常可靠的类型推断支持。今天主要记录一下在Vue3下使用Pinia的使用情况:
一、安装
yarn add pinia
或者
npm install pinia
二、创建Pinia
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
const pinia = createPinia()
createApp(App).use(pinia).mount('#app')
三、定义属性和方法
TypeScript
import { defineStore } from 'pinia'
export const useTemplate = defineStore('useTemplate',{
state:() => ({
count:0
}),
getters:{
doubleCount:(state) =>{
state.count * 2
},
threeCount:(state) => state.count * 3
},
actions:{
addCount(){
this.count ++
},
minusCount(){
this.count --
}
}
})
在state中定义属性,和data类似,getters是定义计算属性,和computed类似,actions定义方法,和methods类似,所以上面的例子也可换种写法:
TypeScript
export const useTemplate = defineStore('useTemplate',() =>{
const count = ref(0)
const doubleCount = computed(() => count1.value * 2)
const threeCount = computed(() => count1.value * 3)
function addCount(){
count1.value ++
}
const minusCount = () =>{
count1.value --
}
return {count,doubleCount,threeCount,addCount,minusCount}
})
四、使用
import { useTemplate} from '@/stores/useStores'
TypeScript
import { useTemplate,useTemplate2 } from '@/stores/useStores'
const store = useTemplate()
//修改属性值
//方法1
store.count += 1
//方法2
store.addCount()
//方法3,重置属性值
store.$reset()
以上就是pinia的简单使用方法,更多复杂的,比如在actions中调用接口,万变不离其宗,都可以根据这种简单的例子来实现