pinia 入门及使用
自上月从上海结束工作回来 在家闲来无事 想写点东西打发时间 也顺便学习学习新的技术。偶然发现了 pinia 据说比vuex好用些 所以便搭了个demo尝试着用了下 感觉确实不错,于是便有了这篇随笔。
那么废话不多说 直接开始吧。(附pinia官网地址:https://pinia.web3doc.top/)
1.安装
yarn add pinia # 或者使用 npm npm install pinia
2.项目中引入
vue2引入方法(直接复制官网的)
import { createPinia, PiniaVuePlugin } from 'pinia' Vue.use(PiniaVuePlugin) const pinia = createPinia() new Vue({ el: '#app', // 其他选项... // ... // 注意同一个 `pinia` 实例可以在多个 Vue 应用程序中使用 // 同一个页面 pinia, })
vue3引入方法 (引入createPinia函数后实例化下 然后直接挂载到vue的use函数即可)
import { createPinia } from 'pinia' const pinia = createPinia() createApp(App).use(pinia).mount('#app')
3.定义一个 Store
在src目录下新建 store 目录 然后新建一个js或者ts文件 然后导入pinia的 defineStore 函数 函数的第一个参数是当前store的 id 相当于key 第二个是一个对象 里面就是我们存放数据的地方了
export default 默认导出是为了方便我们其他页面引用这个store 这样 一个store就定义好了
export default defineStore('defaultStore' ,{
state:() => { return {
count: 1 }
},
getters:{
}, actions:{
setCount(){ this .count++ }
}
})
4.使用store
定义好了之后 那就是怎么使用我们的store了
<template> <div class="root-box"> count == {{store.count}} //3.然后就可以直接使用了 </div> </template> <script setup lang="ts"> import defaultStore from "./../../store" ; //1.引入我们刚刚定义的store
import {onMounted} from 'vue'
const store = defaultStore()//2.实例化一下
onMounted(()=>{
store.count++ //修改store的值
})
</script>
可能有人想问 能不能不用store.count呢 可不可以直接解构赋值。答案是可以的
但是不能直接解构赋值 不然会失去数据的响应性的 我们应该使用pinia提供的 storeToRefs 函数来进行解构
<script setup lang="ts"> import defaultStore from "./../../store" ;
import { storeToRefs } from "pinia" ;
const store = defaultStore()
const { count } = storeToRefs(store) </script>
5.getters&actions
和vuex一样 pinia里 getters是用于获取store的数据的 actions是用来操作store的数据的
getters:{
getCount(state){ return state.count
}
},
actions:{
setCount(){ this .count++ }
}
与上文中直接 store.count 不同。使用getters获取数据时 你可以在获取到数据前对数据进行一些操作。 例:一个数组或一个对象 你想在获取前剔除掉某些不符合要求的数据之类的。
actions同理。
使用过vuex的朋友一定看出了 pinia 其实很多地方和vuex很相似。有使用过vuex经验的人能够非常轻松的上手这个全新的vue存储库,并且写法上比vuex更加简便快捷 更加的容易理解
6.使用上的拓展
除了上述的 store.count的直接修改 和 actions以外 官方还提供了其他几种修改数据的方法
//通过$patch 传入对象 可以一次性修改多个数据
store.$patch({
count: store.count + 1 , })
// 传入函数 这个可以让你在修改数据前进行一些其他的操作 类似于一个单独的actions
store . $patch ( ( state ) => {
store.count = store.count + 1
})
// 也可以直接替换掉整个store
store .$state = { name : 'pinia' }