1. 什么是Pinia
Pinia 是 Vue 的专属的最新状态管理库 ,是 Vuex 状态管理工具的替代品
- 提供更加简单的APl(去掉了mutation,Pinia 中对state数据的修改可以直接通过action,Vuex中则是通过mutation)
- 提供符合组合式风格的API(和Vue3新语法统一)
- 去掉了modules的概念,每一个store都是一个独立的模块
- 配合TypeScript更加友好,提供可靠的类型推断
2. 手动添加Pinia到Vue项目
后面在实际开发项目的时候,Pinia可以在项目创建时自动添加,现在我们初次学习,从零开始:
- 使用 Vite 创建一个空的 Vue3项目
npm init vite@latest
- 安装pinia
npm install pinia
- 使用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')
3. Pinia基础使用
- 定义store
- 组件使用store
定义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>
4. getters实现
Pinia中的 getters 直接使用 computed函数 进行模拟, 组件中需要使用需要把 getters return出去
const count = ref(0)
//getter
const doubleCount = computed(() => count.value *2)
5. action异步实现
方式:异步action函数的写法和组件中获取异步数据的写法完全一致
-
接口地址:http://geek.itheima.net/v1_0/channels
-
请求方式:get
-
请求参数:无
//异步action
const getList = async () => {const res = await axios.request<接口数据类型>({})
}
6. storeToRefs工具函数
使用storeToRefs函数可以辅助保持数据(state + getter)的响应式解构
//响应式丢失,视图不再更新
const { count, doubleCount } = counterStore//保持数据响应式
const { count, doubleCount } = storeToRefs(counterStore)
数据的解构需要通过storeToRefs()才可以保持数据响应式,如果直接解构则是拷贝一份给解构后的数据,如果是方法的解构则直接解构即可,不需要加上storeToRefs()
7. Pinia的调试
Vue官方的 dev-tools 调试工具 对 Pinia直接支持,可以直接进行调试
8. Pinia持久化插件
官方文档:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/
pinia持久化作用等同于localstore
- 安装插件 pinia-plugin-persistedstate
npm i pinia-plugin-persistedstate
- 使用 main.js
// 导入持久化插件,该插件是给pinia使用的
import persist from 'pinia-plugin-persistedstate'
...
app.use(createPinia().use(persist))
- 配置 store/counter.js
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'] }