全新一代状态管理工具Pinia

pinia的优势和安装环境

优势

  • 一个全新vue状态管理库,很好的支持vue2、vue3
  • 摒弃了Mutations的操作,只有state、getters、actions 极大简化了状态库的使用
  • 不需要状态嵌套 是代码扁平化
  • 很好的支持TS语法

安装

pinia是vue的状态管理库因此推荐是使用vite来初始化vue项目

yarn create vite
1

在这里我们选择 vue3 -ts 版本 拥抱最新的编程思想

pinia的安装

npm install pinia 
# or with yarn 
yarn add pinia
1
2
3

使用pinia的使用

在main.ts 里面引入Pinia

import { createPinia } from 'pinia'
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia' 

// 创建pinia 实例
const pinia = createPinia()
const app =createApp(App)
// 挂载到 Vue 根实例上
app.use(pinia)
app.mount('#app')
1
2
3
4
5
6
7
8
9
10
11

先引入mainStore,然后通过mainStore得到store实例,就可以在组件里调用store里的state定义的状态数据了。

<template>
  <h2 class="">{{ store.helloWorld }}</h2>
</template>

<script lang="ts" setup>
import { mainStore } from "../store/index";
const store = mainStore();
</script>

<style lang="scss" scoped></style>
1
2
3
4
5
6
7
8
9
10

创建store状态管理库

import { defineStore} from 'pinia'

export const mainStore = defineStore('main',{
  state:()=>{
    return {}
  },
  getters:{},
  actions:{}
})

1
2
3
4
5
6
7
8
9
10

在组件里读取 store的属性

<template>
  <h2 class="">{{ store.helloWorld }}</h2>
</template>

<script lang="ts" setup>
import { mainStore } from "../store/index";
const store = mainStore();
</script>

<style lang="scss" scoped></style>
1
2
3
4
5
6
7
8
9
10

修改store的属性

<template>
  <div><button @click="handleClick">点击增加</button></div>
</template>

<script lang="ts" setup>
import { mainStore } from "../store/index";
const store = mainStore();

const handleClick = () => {
  store.count++;
};
</script>

<style lang="scss" scoped></style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14

注意解构问题

<template>
  <h2 class="">{{ store.helloWorld }}</h2>
  <h2 class="">{{ store.count }}</h2>
  <hr />
  <h2 class="">{{ helloWorld }}</h2>
  <h2 class="">{{ count }}</h2>
</template>

<script lang="ts" setup>
import { mainStore } from "../store/index";
const store = mainStore();
const { helloWorld, count } = store; //不是响应式数据
</script>

<style lang="scss" scoped></style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const { helloWorld, count } = storeToRefs(store);
1

推荐使用$patch修改多条数据

因为Pinia 的官方网站,已经明确表示$patch的方式是经过优化的,会加快修改速度,对程序的性能有很大的好处。所以如果你是多条数据同时更新状态数据,推荐使用$patch方式更新。

const handleClickPatch = () => {
  store.$patch({
    count: store.count + 2,
    helloworld:'wangzhiwei'
  });
};
1
2
3
4
5
6

pinia状态改变数据的四种方式包括Acitons的使用

Store相互调用的方法

pinia在vue-devtools中调用的方法

Last Updated: 7/13/2022, 11:37:25 AM