Vue的专属老婆---Pinia

一.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)
  }

相比于同步,异步请求会在后端进行不会影响程序,而同步请求会阻塞程序执行,影响用户体验

四.storeToRefs

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值