Pinia 安装和基本使用(安装pipenv)
项目环境 Vue3 + TypeScript + Vite
Pinia 入门到熟悉!
一、 Pinia 内容简介
官网:Pinia (vuejs.org)
Pinia是vue3中的状态管理机,其作用和Vue2的Vuex一样,是一个全新Vue的状态管理库。
二、 Pinia 使用优点
- 与 Vuex 比较,pinia取消了Mutations同步的方法,只有 state getters actions 几个属性,简化了状态库管理操作;
- 使用中不需要集中定义和模块化命名空间的嵌套;
- 完全支持 TypeScript,Vue3的项目最大优势之一就是对TypeScript的支持很理想。
三、 pinia的安装
npm 安装:
npm install pinia
或者使用 yarn
yarn add pinia
四、 创建第一个 Store 实例
项目创建pinia实例之前需要先安装Pinia。
注册 实例化
在main.ts里边引入 pinia状态库,并且实例化:
import { createPinia } from 'pinia'
const store = createPinia()
挂载vue实例上(完整代码):
import { createApp } from 'vue'
import App from './App.vue'
import {createPinia} from 'pinia'
const store = createPinia()
createApp(App).use(ElementPlus).use(router).use(store).mount('#app')
五、 创建第一个 Store 状态管理仓库
我们可以在 /src下创建一个 /store文件夹来专门设置状态管理库,也可以直接在页面的文件夹下面直接创建状态管理库,pinia不需要集中化的管理状态数据,以下主要是创建store文件夹的方式,方便管理。
主要操作:
(1)初始化定义状态;
(2)修改仓库的 state;
(3)对 action的使用。
创建 /src/store/index.ts:
import { defineStore } from 'pinia'
export const indexStore = defineStore('index', {
state: ()=>{
return {}
},
getters: {},
actions: {}
})
- 解释:
- defineStore():创建仓库容器的方法,主要有两个参数,第一个参数是容器的一个别名,特点:此名字必须唯一,不能重复,第二个参数是配置信息即仓库的初始化数据和方法
- state:用来存储全局状态
- getters:计算属性,用来监听或者计算状态变化的,有缓存功能
- actions:状态修改,用来对 state 里数据进行管理和操作
六、 在项目中里使用pinia
1. 创建页面和使用仓库
- 在/scr/views里创建一个二级页面Hello.vue`:
- 先引入indexStore,得到 pinia的store的实例,进而得到store里定义的状态数据
- 解构pinia的数据来使用和双向绑定,使用官方提供的storeToRefs()方法
- 注意: 直接解构数据不是响应式的,踩的大坑都是泪
<template>
<h3>{{store.helloWorld}}</h3>
<h3>解构:{{ helloWorld }}</h3>
</template>
<script lang="ts" setup>
import { indexStore } from "../store"
import { storeToRefs } from "pinia"
const store = indexStore()
// 解构:
const { helloWorld } = storeToRefs(store)
</script>
<style></style>
```
#### 2. 运行项目
根据自己配置的运行命令执行 默认 npm run dev或者 yarn dev
### 七、 修改仓库状态数据的方法
#### 1. 状态获取
```xml
<script lang="ts" setup>
import { indexStore } from "../store";
const store = indexStore()
// 方法一
const update = () => {
store.helloWorld = 'hello world'
}
</script>
2. $patch的两种方法
<script lang="ts" setup>
import { indexStore } from "../store";
const store = indexStore()
// 方法二
const handleClickPatch = () => {
store.$patch({
helloWorld: 'hello world patch'
})
}
// 方法三-使用$patch回调函数
const handleClickMethod = () => {
store.$patch((state)=>{
state.helloWorld = 'hello world method'
})
}
</script>
3. 使用actions
注意actions中的this指向,这里不能使用箭头函数
- 在/store中:
import { defineStore } from 'pinia'
export const indexStore = defineStore('main', {
state: ()=>{
return {
helloWorld: 'Hello world!'
}
},
getters: {},
actions: {
actionChange() {
this.helloWorld = 'hello world actions'
},
},
})
- 在/Hello中:
<script lang="ts" setup>
import { indexStore } from "../store";
const store = indexStore()
// 方法四
const handleClickActions = () => {
store.actionChange()
}
</script>
八、Getters的使用
Pinia中的Getters没有太多的新的变动,整体的使用和语法和Vuex的计算属性几乎一致,可参考vuex的计算属性。