pinia介绍与使用
介绍
官方文档
Pinia是Vue生态里Vuex的代替者,一个全新Vue的状态管理库,语法更加简洁;在推出vue3后,强烈推荐使用pinia代替vuex,因为它支持Composition api 和 对TypesScript的完美支持。
安装
npm install pinia
项目中引入Pinia
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
const app = createApp(App);
app.use(createPinia())
app.mount('#app')
新建Store
在src的根目录下新建 store\index.ts
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
state:()=>{
return {
count: 0,
status: true
}
},
getters:{},
actions:{}
})
改变pinia的状态数据
使用storeToRefs( )会对结构的数据处理起到响应式的效果
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useStore } from '../store/index'
const user = useStore();
//storeToRefs
const { count, status } = storeToRefs(user);
const handClick=()=>{
user.count++
}
</script>
<template>
<h3>{{count}}</h3>
<button @click="handClick">增加</button>
</template>
使用$path 修改多条状态数据
<script setup lang="ts">
import { useStore } from '../store/index'
const user = useStore();
const handClick=()=>{
user.$patch((state)=>{
{
state.status = user.count > 10 ? false : true,
state.count = user.status ? user.count+1:user.count-1
}
})
}
</script>
Actions 通过函数更改状态
在store\index文件中actions函数中添加changeState()方法,然后再组件中通过store直接调用
// store\index.ts
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
state:()=>{
return {
count: 0,
status: true
}
},
getters:{},
actions:{
changeState(){
this.count++;
}
}
})
// 组件中通过store直接调用
<script setup lang="ts">
import { useStore } from '../store/index'
const user = useStore();
const handClick=()=>{
user.changeState()
}
</script>
Getters类似vuex的计算属性
手机号码中间四位显示*号
在store\index文件中Getters函数中添加phoneHidden()方法,然后再组件中通过store直接调用
//在store\index
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
state:()=>{
return {
count: 0,
status: true,
phone: '15898970112'
}
},
// getters
getters:{
phoneHidden(state){
return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}
},
actions:{
changeState(){
this.count++;
}
}
})
//组件中
<h3>电话号码{{user.phoneHidden}}</h3>