1,pinia是什么
Pinia 是 Vue.js 的轻量级状态管理库
pinia与vuex4的区别
相同:
是vue 官方 状态管理工具(作者是 Vue 核心团队成员)
是vue开发者工具支持pinia
不同:
pinia相比vuex4,对于vue3的 兼容性 更好
pinia相比vuex4,具备完善的 类型推荐
Pinia 的 API 设计非常接近 Vuex 5
的提案。
vuex只能有一个根级别的状态, pinia 直接就可以定义多个根级别状态
pinia核心概念
state: 状态
actions: 修改状态(包括同步和异步,pinia中没有mutations)
getters: 计算属性
2,pinia基本使用
在main.js中引入pinia:
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
const pinia = createPinia()
createApp(App).use(pinia).mount('#app')
定义模块:
import { defineStore } from 'pinia'
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters
export default defineStore('counter', {
state: () => {
return {
count: 0,
}
},
getters: {
},
actions: {
},
})
使用模块:
<script setup lang="ts">
import useCounterStore from './store/counter'
const counter = useCounterStore()
</script>
<template>
<h1>{{ counter.count }}</h1>
</template>
<style></style>
3,pinia中actions的使用
actions:
在pinia中没有mutations,只有actions,不管是同步还是异步的代码,都可以在actions中完成
定义action:
在actions中提供方法并且修改数据。在action的内部,修改数据采用的是: this.状态 = 新值
的格式
import { defineStore } from 'pinia'
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters
export default defineStore('counter', {
state: () => {
return {
count: 0,
}
},
actions: {
increment() {
this.count++
}
},
getters: {
}
})
在组件中使用 :
<script setup>
import useCounterStore from './store/counter'
const counter = useCounterStore()
</script>
<template>
<button @click="counter.increment">加1</button>
</template>
注意:
pinia中,合并了原vuex中的action和mutation的概念
4,pinia中getters的使用
定义getters:
在getters中提供计算属性
import { defineStore } from 'pinia'
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters
export default defineStore('counter', {
state: () => {
return {
count: 0,
}
},
getters: {
double() {
return this.count * 2
}
},
actions: {
},
})
在组件中使用:
<script setup>
import useCounterStore from './store/counter'
const counter = useCounterStore()
</script>
<template>
<h1>{{ counter.count }}</h1>
<h3>{{ counter.double }}</h3>
</template>