Pinia初探
1.Pinia简介
Pinia
也是状态管理工具,相比于vuex
Pinia
的优势:
vue3、vue2
中都可以使用的- 抛弃了
Mutations
的操作,只有state、getters和actions
- 不需要嵌套模块,符合
vue3
的Composition api
- 支持
typescript
- 能够让代码更加简介
pinia
需要vue
环境,在vue
官网上

这里我们使用typescript
和Pinia
直接默认安装就可以的了,主要还是来体验下pinia
在数据传递的使用上,带来的体验是否真的便捷。
2.使用Pinia
创建一个store
:
那么在store
文件夹中,主要是做一下几点
- 定义状态容器和状态
- 修改状态容器中的
state
store
仓库中的action
的使用
工具自动生成的store
目录中的内容如下:
stores └─ index.ts
//index.ts 代码如下
import { defineStore } from 'pinia';
export const mainStore = defineStore('main',{
state:()=>{
return {
girlFriend:'yss'
}
},
getters:{},
actions:{},
})
store
的创建是通过defineStore
定义的defineStore
是它的唯一
名称
在HelloPinia.vue
中Pinia
的使用(setup
的情况)
// HelloPinia.vue
<script lang="ts">
import {mainStore} from '@/stores/index';
export default {
setup(){
const myStore = mainStore();
return {
myStore
};
}
}
</script>
<template>
<p>这个是我的女朋友{{myStore.girlFriend}}</p>
</template>
<style scoped>
</style>
运行结果如下:

3.使用Pinia
改变状态数据和注意事项:
下面的要借助与一个计数器的案例,来看下Pinia
对于数据的改变
先来看下
store
中的counter.ts
//counter.ts
import { ref } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
return { count }
})
在HelloCounter.vue
组件中修改状态
// HelloCounter.vue
<template>
<div>
<p>{{store.count}}</p>
<button @click="handleClick">修改数据状态</button>
</div>
</template>
<script setup lang="ts">
import { useCounterStore } from '@/stores/counter';
const store = useCounterStore();
const handleClick = ()=>{
store.count++;
};
</script>
<style scoped>
</style>
有时候需要,store
中定义的状态太多了的,不想要store.count
的形式,故而想要对store
进行解构
==> const {count} = store
这里需要注意的是,store
是一个用reactive
包裹的对象。
如果想用解构
的方法,那么pinia
提供了一个方法storeToRefs
,将reactive
对象转为普通的对象
====> const {count } =storeToRefs(store);
点击修改数据按钮
结果如下图:

4.Pinia修改数据状态的方式:
a)直接通过store.count++;
b)$patch + 对象:
在修改多条数据的情况下
-
//$patch const changeStateByPatch = ()=>{ store.$patch({ count:stroe.count + 520, }) }
c)$patch + 箭头函数
-
const changeStateByPatch = ()=>{ store.$patch((state)=>{ state.count ++ }); }
d)业务逻辑写到store文件的"action"
// counter.ts
import { ref } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
function increment() {
count.value++
}
return { count, increment }
})
最后的最后,感谢观看,今天也是爱你的一天哟,莎老板
,此篇也只是对官网内容的整理,感受下Pinia
带来的体验,更多的可能还需要在实际项目中更好的去感受吧。
转载自:https://juejin.cn/post/7160545900446613534