Pinia
为vue设计的一个现代化的状态管理库,vue3生态系统中的一个核心组件,
专为利用Vue3的新特性设计,替代Vuex称为Vue应用的状态管理标准,提供了更简洁的API,更好的类型安全,以及易于调试的功能
状态管理
在前端应用开发中,用来集中管理和协调应用程序状态的一种工具.在这里指的是像用户登录信息,UI状态,列表数据等需要被多个组件共享或者跨组件同步的一些应用程序运行时的数据.
使用方法
创建store
import { defineStore } from 'pinia'
//创建一个store,需要通过defineStore方法创建,并且指定名称和state、getter、actions
export const useMyCounterStore = defineStore('myCounter', {
// 定义state,一般都设置的
state: () => {return {count : 1}},
// 定义getter,可以省略
getters: {
double : (state) => state.count * 2
},
//定义actions,一般都设置的
actions: {
increment(){
this.count++;
}
}
})
在ts文件中定义一个store,对一个响应式对象,响应式对象的映射,响应式对象的方法等进行封装
使用store
<script>
import store from 创建的store
</script>
<template>
以{{ store.属性 }}的方式进行使用
也可以通过@click='store.方法'的方式进行绑定
</template>
使用组合式的方式编写
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
//分别指:state、getter、actions
return { count, doubleCount, increment }
})
将属性方法和computed()映射的结果写在一个方法内进行export导出
持久化插件
将store数据存储到浏览器的localStorage中
在main.js中进行引入和使用
import persist from 'pinia-plugin-persistedstate'
//引入持久化插件
app.use(createPinia().use(persist))
//使用持久化
//并在创建的store中开启持久化
persist:true
使用场景:优化前端的重复请求
在之前多个组件调用同一个组件时
会多次调用这个组件中的同一个方法
现在可以通过pinia实现组件中数据的共享