Pinia

1,pinia是什么

        Pinia 是 Vue.js 的轻量级状态管理库

pinia与vuex4的区别

        相同:

                是vue 官方 状态管理工具(作者是 Vue 核心团队成员)

                是vue开发者工具支持pinia

        不同:

                pinia相比vuex4,对于vue3的 兼容性 更好

                pinia相比vuex4,具备完善的 类型推荐

                Pinia 的 API 设计非常接近 Vuex 5 的提案。

                vuex只能有一个根级别的状态,  pinia 直接就可以定义多个根级别状态

pinia核心概念

        state: 状态

        actions: 修改状态(包括同步和异步,pinia中没有mutations)

        getters: 计算属性

         

2,pinia基本使用

        在main.js中引入pinia:

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

import { createPinia } from 'pinia'
const pinia = createPinia()

createApp(App).use(pinia).mount('#app')

         定义模块:

import { defineStore } from 'pinia'
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters
export default defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  },
  getters: {
   
  },
  actions: {
    
  },
})

        使用模块:

<script setup lang="ts">
import useCounterStore from './store/counter'

const counter = useCounterStore()
</script>

<template>
  <h1>{{ counter.count }}</h1>
</template>

<style></style>

   

3,pinia中actions的使用 

actions:

        在pinia中没有mutations,只有actions,不管是同步还是异步的代码,都可以在actions中完成

定义action:

        在actions中提供方法并且修改数据。在action的内部,修改数据采用的是: this.状态 = 新值的格式 

import { defineStore } from 'pinia'
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters
export default defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  },
  actions: {
    increment() {
      this.count++
    }
  },
  getters: {
   
  }
})

 在组件中使用 :

<script setup>
import useCounterStore from './store/counter'

const counter = useCounterStore()
</script>

<template>
  <button @click="counter.increment">加1</button>
</template>

注意:

        pinia中,合并了原vuex中的action和mutation的概念

 

4,pinia中getters的使用

         定义getters:

                在getters中提供计算属性

import { defineStore } from 'pinia'
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters
export default defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  },
  getters: {
    double() {
      return this.count * 2
    }
  },
  actions: {
    
  },
})

        在组件中使用:

<script setup>
import useCounterStore from './store/counter'

const counter = useCounterStore()
</script>

<template>
  <h1>{{ counter.count }}</h1>
  <h3>{{ counter.double }}</h3>
</template>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值