前言:自己做笔记给自己看的
Pinia
文档:pinia.vuejs.org/zh/introduc…
概念:Pinia 是 Vue 的专属状态管理库,它允许你跨组件或页面共享状态。
和之前的vuex的区别:
Vuex和Pinia都是vue.js的状态管理工具,Vuex是vue2使用,而在vue3推荐了Pinia,主要有以下几点区别:
- Pinia没有mutation,他只有state,getters,action【同步、异步】使用它来修改state数据
- Pinia语法上比vuex更容易理解和使用,灵活。
- Pinia没有modules配置,每一个独立的仓库都是definStore生成出来的、
- Pinia的state是一个在函数中返回的对象,和vue组件中的data编写方式差不多
vuex的不足 :
Pinia和Vuex都是非常好用的数据管理工具,在某些情况下,使用Pinia的web应用程序会比使用Vuex更快,这种性能的提升可以归因于Pinia的极轻的重量,Pinia体积约1KB。
安装:
yarn add pinia
# 或者使用 npm
npm install pinia
在main.js或者是main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
在store文件夹中创建index.js
import {defineStore} from 'pinia'
export default defineStore('main',
{
state:()=>{
return {
count:10,
name:"小明",
num:2
}
},
// 计算属性
getters:{
newcount:(state)=>{
return state.count * state.num
}
},
// 同步异步都可以
actions:{
// this就是store
changeCount(){
console.log('this',this);
this.count++
}
}
})
别的页面使用store文件夹中index.js的数据
<script setup lang="ts">
import useMain from './store/store'
import { storeToRefs } from 'pinia'
const store = useMain()
let {count} = storeToRefs(store)
function add(){
store.count++
}
function pathch(){
// 这种是一起修改 多个一起修改
// store.$patch({
// count:store.count+1,
// name:6666
// })
// state参数 他的值其实就是store
// store.$patch((state:any)=>{
// state.count = 5;
// state.name = 8888
// })
// 整个替换掉
store.$state = {
count:800,
name:'wwp'
}
}
// 重置一下仓库的数据
function resState(){
store.$reset()
}
// 监听整个仓库的变化
store.$subscribe((mutation,state)=>{
console.log('mutation',mutation);
console.log('state',state);
})
</script>
另外一种方式
store文件里面的index.ts
import {defineStore} from 'pinia'
export const useMainStore:any = defineStore('main',
{
state:()=>{
return {
count:10,
name:"小明",
num:2
}
},
// 计算属性
getters:{
// 这个是有缓存的,如果调用多次,他只执行前面的一次
newcount(state){
console.log("我被触发了")
return state.count * state.num
}
},
// 同步异步都可以
actions:{
// this就是store 不要写成箭头函数,写成箭头函数就没有this
changeCount(){
console.log('this',this);
this.count++
}
}
})
使用的时候
<script setup lang="ts">
import {
useMainStore
} from '../store/index'
import {
storeToRefs
} from 'pinia'
//获取到他们的值和方法
const main = useMainStore();
// console.log(main)
// 还有一种方式是使用 他官方提供解构赋值
// 提供的结构赋值 newcount是计算属性来的
let {
name,
count,
newcount
} = storeToRefs(main)
// 修改的方式
let changeBtn = () => {
// 方式一,简单的修改
// main.count ++
// 方式二,提供的方式的修改,类似小程序修改数值一样 可以批量修改
// main.$patch({
// count:main.count+1
// })
// 方式三:一个箭头函数 store
// main.$patch((store:any)=>{
// // 这函数里面的可以直接修改store 的值
// store.count++
// store.name = "靓仔"
// })
// 方式四,直接调用里面的action的方法
main.changeCount();
}
</script>