Pinia 是 Vue 的专属的最新状态管理库 ,是 Vuex 状态管理工具的替代品
后面在实际开发项目的时候,Pinia可以在项目创建时自动添加,现在我们初次学习,从零开始:
npm init vite@latest
npm install pinia
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(state+action)store/counter.js
store/counter.js
import { defineStore } from "pinia";
import { computed, ref } from 'vue'
export const useCounterStore = defineStore('counter', () => {
//数据 (state)
const count = ref(0)
//修改数据的方法 (action)
const increment = () => {
count.value++
}
const sub = () => {
count.value--
}
// getter,用computed实现
const doubleCount = computed(() => count.value * 2 )
// 以对象形式返回
return { count, increment, sub, doubleCount}
})
Son1.vue
<script setup>
defineOptions({
name: 'Son1Index'
})
// 1. 导入`useCounterStore`方法
import { useCounterStore } from '@/stores/counter'
// 2. 执行方法得到counterStore对象
const counterStore = useCounterStore()
script>
<template>
<div>
我是Son1.vue {{ counterStore.count }} <button @click="counterStore.increment">+button>
div>
template>
<style>
style>
Pinia中的 getters 直接使用 computed函数 进行模拟, 组件中需要使用需要把 getters return出去
const count = ref(0)
//getter
const doubleCount = computed(() => count.value *2)
方式:异步action函数的写法和组件中获取异步数据的写法完全一致
接口地址:http://geek.itheima.net/v1_0/channels
请求方式:get
请求参数:无
//异步action
const getList = async () => {
const res = await axios.request<接口数据类型>({})
}
使用storeToRefs函数可以辅助保持数据(state + getter)的响应式解构
//响应式丢失,视图不再更新
const { count, doubleCount } = counterStore
//保持数据响应式
const { count, doubleCount } = storeToRefs(counterStore)
数据的解构需要通过storeToRefs()才可以保持数据响应式,如果直接解构则是拷贝一份给解构后的数据,如果是方法的解构则直接解构即可,不需要加上storeToRefs()
Vue官方的 dev-tools 调试工具 对 Pinia直接支持,可以直接进行调试
官方文档:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/
pinia持久化作用等同于localstore
npm i pinia-plugin-persistedstate
// 导入持久化插件,该插件是给pinia使用的
import persist from 'pinia-plugin-persistedstate'
...
app.use(createPinia().use(persist))
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
export const useCounterStore = defineStore('counter', () => {
...
return {
count,
doubleCount,
increment
}
}, {
persist: true
})
其他配置,看官网文档即可
如果不打算持久化整个counter,可以指定具体的属性,
persist:{
paths: ['count','doubleCount']
}