1. 添加pinia到vue项目
1.1 什么是pinia
Pinia是Vue的专属的最新的 状态管理库,是Vuex状态管理工具的替代品。
- 提供更加简单的API(去掉了 mutation)
- 提供符合组合式风格的API(和Vue3新语法统一)
- 去掉了modules的概念,每一个store都是一个独立的模块
- 搭配typescript一起使用,提供可靠的类型判断
1.2 添加pinia到Vue项目
- 使用 create-vue创建空的新项目
npm init vue@latest
- 安装官方文档安装 pinia到项目
npm install pinia
- 创建一个pinia实例(根store)并将其传递给应用
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia ()
createApp(App).use(pinia).mount('#app')
2. counter基础使用
2.1 使用Pinia实现计数器案例
- 定义Store(state + action)counter.js
- 组件使用(Store)App.vue
// 导入一个方法 defineStore
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', ()=> {
// 定义数据(state)
const count = 0
// 定义修改数据的方法(action 同步+异步)
const increment = () => {
count.value++
}
// 以对象的方式return供组件使用
return {
count, increment
}
})
// 1.导入use打头的方法
import { useCounterStore } from '@/stores/counter'
// 2.执行方法得到store实例对象
const counterStore = useCounterStore()
// 3.调用
counterStore.count
counterStore.increment
3. getters和异步action
3.1 getters实现
Pinia中使用getters直接使用 computed函数 进行模拟
// 数据(state)
const count = ref(0)
// getter
const doubleCount = computed(() => count.value * 2)
3.2 action如何实现异步
action中实现异步和组件中定义数据和方法的风格完全一致
const APL_URL = 'http://geek.itheima.net/v1_0/channels'
// 准备数据(state)
const list = ref([])
// 异步action
const loadList = async () => {
const res = await axios.get(API_URL)
list.value = res.data.data.channels
}
4. storeToRefs和调试
使用storeToRefs函数可以辅助保持数据(state + getter)的响应结构
// 响应式丢失 视图不再更新
const { count, doubleCount } = counterStore
// 响应式丢失 视图不再更新
const { count, doubleCount } = counterStore
// 保持数据响应式
const { count, doubleCount } = storeToRefs(counterStore)
App.vue
<script setup>
// 1.导入user打头的方法
import { useCounterStore } from '@/stores/counter'
import { omMounted } from 'vue'
import { storeToRefs } from 'pinia'
// 2.执行方法得到store实例对象
const counterStore = useCounterStore()
console.log(counterStore)
// 直接解构赋值(响应式丢失)
const { count, doubleCount } = counterStore
// storeToRefs方法包裹(保持响应式更新)
const { count, doubleCount } = storeToRefs(counterStore)
// 方法直接从原来的counterStore中解构赋值
const { increment } = counterStore
// 触发action
onMounted(() => {
counterStore.getList()
})
</script>
<template>
<button @click='increment'>{{ count }}</button>
{{ doubleCount }}
</template?
调试工具
5. 总结
- pinia是用来做什么的?
集中状态管理工具,新一代的vuex - pinia中还需要mutation吗?
不需要,action既支持同步也支持异步 - pinia如何实现getter?
computed计算属性函数 - pinia产生的store如何解构赋值数据保持响应式?
storeToRefs(注:storeToRefs只能解构赋值数据,解构方法的话还需要基于原本store)