pinia基本使用
1、安装
npm install pinia
2、在main.js中引入pinia并创建容器挂载到根实例上
import App from './App.vue'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
const app = createApp(App)
app.use(createPinia())
3、在stores文件夹下创建counter.js文件。这个文件就是存有关counter相关的数据。(类似vuex的模块化)
//选项式写法========================================================
//定义关于counter的store
import {defineStore} from 'pinia'
/*defineStore 是需要传参数的,其中第一个参数是id,就是一个唯一的值,
简单点说就可以理解成是一个命名空间.
第二个参数就是一个对象,里面有三个模块需要处理,第一个是 state,
第二个是 getters,第三个是 actions。
*/
const useCounter = defineStore("counter",{
state:() => ({
count:66,
}),
getters: {
// 类似计算属性 可以接收到的state参数
// 写法一 使用state参数 可以写成箭头函数,因为没用到this
doubleCount:state => state.count * 2,
// 写法二 使用this,写成普通函数
doubleCount2() {
return this.count * 2
}
},
actions: {
add(value:number){
this.count += value
}
}
})
//暴露这个useCounter模块
export default useCounter
// 组合式写法==================================================
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function add() {
count.value++
}
return { count, doubleCount, add}
})
4、在组件中使用
<template>
<!-- 在页面中直接使用就可以了 不用 .state-->
<div>展示pinia的counter的count值:{{counterStore.count}}</div>
</template>
<script setup>
// 首先需要引入一下我们刚刚创建的store
import useCounter from '../stores/counter'
// 因为是个方法,所以我们得调用一下
const counterStore = useCounter()
</script>
5、修改数据
function add(){
//第一种方式(多次操作)
counterStore.count++
counterStore.name = '小李'
// 第二种修改方式(一次操作,批量变更推荐用法)
counterStore.$patch({
count: 100,
name: '小李'
})
// 第三种修改方式(适用于逻辑复杂并且可以复用的场景)
counterStore.add(10)
}
6、注意Store获取到后不能解构,否则失去响应式,解构的话需要用pinia提供了一个函数storeToRefs
import { storeToRefs } from "pinia";
// 错误,会失去响应式
// const { count, name, doubleCount } = counterStore
// 错误,这样会把里面所有的属性方法都变成响应式
// const { count, name, doubleCount } = toRefs(counterStore)
// 正确解构
const { count, name, doubleCount } = storeToRefs(counterStore)
7、$subscribe
// 有点像watch
counterStore.$subscribe((mutate, state)=>{
console.log('可以收到两个参数,mutate本次修改信息(不太关心),state',mutate, state);
})
8、数据持久化
npm install pinia-plugin-persistedstate
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
pinia.use(piniaPluginPersistedstate);
app.use(pinia);
更多persist配置:配置 | pinia-plugin-persistedstate