Pinia

Pinia 是 Vue 的专属的最新状态管理库 ,是 Vuex 状态管理工具的替代品

  1. 提供更加简单的API(去掉了 mutation)
  2. 提供符合组合式风格的API(和 Vue3 新语法统一)
  3. 去掉了 modules 的概念,每一个 store 都是一个独立的模块
  4. 搭配 TypeScript 一起使用提供可靠的类型推断

添加Pinia到Vue项目

  1. 使用 create-vue 创建空的新项目
npm init vue@latest
  1. 按照官方文档安装 pinia 到项目

安装

  1. 安装
 yarn add pinia  /  npm install pinia
  1. 配置/main.js
import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'

// 1. 导入createPinia
import { createPinia } from 'pinia'

// 2. 执行方法 得到实例
const pinia = createPinia()

// 3. 把pinia实例加入到app应用中
createApp(App).use(pinia).mount('#app')
  1. 使用
    定义 Store:
    // stores/counter.js
// 导入一个方法 defineStore

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', () => {
// 定义数据(state)
const count = ref(0)

// 定义修改数据的方法(action 同步+异步)
const increment = () => {
count.value++
}

// 以对象的方式 return 供组件使用
return {
count,
increment
}
})

组件使用:

<script setup>
// 1. 导入 use 打头的方法
import { useCounterStore } from '@/stores/counter'
// 2. 执行方法得到实例对象
const counterStore = useCounterStore()
</script>

<template>
<button @click="counterStore.increment()">{{ counterStore.count }}</button>
</template>

<style scoped>
</style>

Getters实现

Pinia中的 getters 直接使用 computed 函数 进行模拟。
Getter 完全等同于 store 的 state 的计算值。

  1. getter定义// stores/counter.js
const doubleCount = computed(() => count.value)
  1. 组件使用
<template>
<button @click="counterStore.increment">{{ counterStore.count }}</button>
{{ counterStore.doubleCount }}
</template>

Action

Action 相当于组件中的 method。、
action中实现异步和组件中定义数据和方法的风格完全一致
// stores/counter.js

const API_URL = 'http://geek.itheima.net/v1_0/channels'
  1. 定义异步action:
    const list = ref()
    const getList = async () => {
    const res = await axios.get(API_URL)
    list.value = res.data.data.channels
    }
  1. 组件使用:
onMounted(()=>{
counterStore.getList()
})
<ul>
<li v-for="item in counterStore.list" :key="item.id">{{ item.name }}</li>
</ul>

storeToRefs

使用 storeToRefs函数 可以辅助保持数据 (state+getter) 的响应式解构// stores/counter.js

// 直接解构赋值(响应式丢失)
// const { count, doubleCount } = counterStore

// 方法包裹(保持数据响应式)
const { count, doubleCount } = storeToRefs(counterStore)

// 方法直接从原来的 counterStore 中解构赋值
const { increment } = counterStore

storeToRefs 和 toRefs 都可以将对象转换为具有 .value 的 ref 对象集合。
区别:

  • storeToRefs 是针对 pinia 的 store 对象

  • toRefs 是 Vue 3 中的通用函数,用于处理任意的响应式对象

总结:

请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值