Pinia理解【Vue3】

什么是Pinia

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

优势:

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

添加Pinia到Vue项目

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

在这里插入图片描述
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')

使用Pinia实现计数器案例

App.vue

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

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

<style scoped>
header {
  line-height: 1.5;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }
}
</style>

counter.js

// 导入一个方法 defineStore
import {defineStore} from 'pinia'
import {ref} from 'vue'

export const useCounterStore = defineStore('counter', ()=>{
    //定义数据(state)
    const count = ref(0)
    // 定义修改数据的方法(action 同步+异步)
    const increment = ()=>{
        count.value++
    }

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

getters实现

Pinia中的 getters 直接使用 computed函数 进行模拟

//定义数据(state)
    const count = ref(0)
// getter定义
    const doubleCount = computed(() => count.value * 2)

action如何实现异步

action中实现异步和组件中定义数据和方法的风格完全一致

 // 定义异步action
    const list = ref([])
    const getList = async ()=>{
        const res = await axios.get(API_URL)
        list.value = res.data.data.channels
    }

storeToRefs

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

//响应式丢失 视图不再更新
const {count, doubleCount} = counterStore
// 保持数据响应式
const {count, doubleCount} = storeToRefs(counterStore)

总结:

  1. Pinia是用来做什么的?
    集中状态管理工具,新一代的vuex
  2. Pinia中还需要mutation吗?
    不需要,action既支持同步也支持异步
  3. Pinia如何实现getter?
    computed计算属性函数
  4. Pinia产生的Store如何解构赋值数据保持响应式?
    storeToRefs
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值