共计 3110 个字符,预计需要花费 8 分钟才能阅读完成。
一. 安装及使用 Pinia
1. 安装 Pinia 两种方式都可,根据个人习惯来
npm install pinia
yarn add pinia
2. 在 main.ts 中引入并挂载到根实例
// src/main.ts
import {createApp} from 'vue'
import App from './App.vue'
import {createPinia} from 'pinia'
// 创建 Vue 应用实例
// 实例化 Pinia
// 以插件形式挂载 Pinia 实例
createApp(App).use(createPinia()).mount('#app')
3.src 目录下新建 store/study/index.js 并写入
Store 是用 defineStore()定义的,它的第一个参数是一个独一无二的 id,也是必须传入的,Pinia 将用它来连接 store 和 devtools。
defineStore()第二个参数可接受两类值:Setup 函数或 Options 对象
state 属性:用来存储全局的状态的,这里边定义的,就可以是为 SPA 里全局的状态了。
getters 属性:用来监视或者说是计算状态的变化的,有缓存的功能。
actions 属性:对 state 里数据变化的业务逻辑,需求不同,编写逻辑不同。说白了就是修改 state 全局状态数据的。
第一种 Options 式写法:
import {defineStore} from 'pinia'
// `defineStore()` 的返回值命名最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾
export const useStudyStore = defineStore('studyId', {state: () => {
return {counter: 0,}
},
getters:{},
actions:{}})
在 Options 式中:Store 的数据 (data),getters 是 Store 的计算属性 (computed), 而 actions 则是 Store 的方法(methods)。
第二种 Setup 式写法:
import {defineStore} from 'pinia'
// `defineStore()` 的返回值命名最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾
export const useStudyStore = defineStore('studyId', ()=>{const count = ref(0)
const name = ref('Ghmin')
const computedTest= computed(() => count.value * 99)
function int() {count.value++}
return {count, name, computedTest, int}
})
在 Setup 式中:ref()成为 state属性,computed()变成 getters,function变成actions
4. 使用 Store
使用上面两种方式其中一种后,便可以在组件中使用 Store 了。
二. 具体使用及属性与方法
1. 定义数据
import {defineStore} from 'pinia'
export const useStudyStore = defineStore('studyId', {state: () => {
return {
name: 'Ghmin',
num:0
}
},
})
2. 组件中使用
vue 组件
{{name}}
注:pinia 可以直接修改 state 数据,无需像 vuex 一样通过 mutations 才可以修改,所以上面的 let {name} = store 这种解构是不推荐的,因为它破坏了响应性。
而为了从 Store 中提取属性,同时保持其响应性,这里需要使用 storeToRefs(),它将为每个响应性属性创建引用。当你只使用 Store 的状态而不调用任何 action 时,它会非常有用。使用方法如下
vue 组件
{{name}}
如果有多条数据要更新状态,推荐使用 $patch 方式更新。因为 Pinia 的官方网站,已经明确表示 $ patch 的方式是经过优化的,会加快修改速度,对程序的性能有很大的好处。
A 组件
{{num}}
{{arr}}
actions: 对 state 里数据变化的业务逻辑,需求不同,编写逻辑不同。说白了就是修改 state 全局状态数据的。
import {defineStore} from 'pinia'
export const useStudyStore = defineStore('studyId', {state: () => {
return {num: 0}
},
getters:{},
actions:{changeNum( val){this.num+= val;}
}
})
使用 actions
{{num}}
getters: 和 vuex 的 getters 几乎类似,用来监视或者说是计算状态的变化的,有缓存的功能。
import {defineStore} from 'pinia'
export const useStudyStore = defineStore('studyId', {state: () => {
return {num: 0,}
},
getters:{numGetters(){return this.counter + 999;}
},
actions:{}})
getters 的使用
{{num}}
{{numGetters}}
三. 数据持久化存储
使用 pinia-plugin-persist 实现数据持久化存储,具体使用请跳转Pinia 持久化存储
数据持久化存储
原文地址: 快速搞懂 Pinia 及数据持久化存储(详细教程)