一.Pinia
1.Pinia概述
Pinia是Vue的专属的最新状态管理库,是Vuex状态管理工具的替代品
- 提供更简单的API(去掉mutation)
- 提供符合组合式风格的API(和Vue3统一)
- 去掉modules的概念,每个store都是独立模块
- 搭配TypeScript一起使用提供可靠的类型推断
//1.导入方法
import { createPinia } from 'pinia'
//2.创建pinia实例
const pinia = createPinia()
//2.加入实例pinia
createApp(App).use(pinia).mount('#app')
二.Counter
定义Store(state + action)
pinia提供了defineStore函数,包含了数据count和修改数据方法doubleCount和自增increment,再以对象的形式返回数据和方法。导出组件后被导入使用就可以正常使用该组件内的数据和方法。
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
//导出
export const useCounterStore = defineStore('counter', () => {
//1.定义数据
const count = ref(0)
//2.定义修改数据的方法 action (同步) computed(异步)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
//3.以对象的形式返回数据和方法
return { count, doubleCount, increment }
})
组件使用Store
<script setup >
//1.导入use打头的方法
import { useCounterStore } from '@/stores/counter.ts'
//2。执行方法得到store实例对象
const counterStore = useCounterStore()
//3.使用store实例对象的方法
counterStore.increment()
console.log(counterStore.count)
</script>
<template>
<button @click="counterStore.increment()">{{ counterStore.count }}</button>
</template>
三.getters实现和异步action
Pinia中的getters直接使用computed函数进行模拟
//1.定义数据(store)
const count = ref(0)
//2.定义方法 getter computed(异步)
const doubleCount = computed(() => count.value * 2)
action实现异步和组件中的定义数据和方法的风格完全一致
const list = ref([])
const getList = async () => {
const res = await axios.get(APIURL)
}
相比于同步,异步请求会在后端进行不会影响程序,而同步请求会阻塞程序执行,影响用户体验