pinia与vuex的区别以及pinia的使用

###pinia 与 vuex 的区别
pinia 的优点 :
完整的 TypeScript 支持:与在 Vuex 中添加 TypeScript 相比,添加 TypeScript 更容易
极其轻巧(体积约 1KB)
store 的 action 被调度为常规的函数调用,而不是使用 dispatch 方法或 MapAction 辅助函数,这在 Vuex 中很常见
支持多个 Store
支持 webpack 代码拆分
vuex 的优点
适用于大型、高复杂度的 Vue.js 项目
何时使用 pinia,何时使用 vuex
pinia 是比较轻量级的,体积小,与 ts 兼容更容易,适用于复杂度低一点 vue 项目,vuex 适用于大一点的高复杂的 vue 项目

###pinia 的使用
(1) 安装 pinia
···npm i pinia···
main.ts 或 main.js 中

import { createPinia } from "pinia";
createApp(App).use(createPinia());

(2)建立新的文件夹 store

import {defineStore} from 'pinia'

// 1 定义容器 并导出
export const myPiniastate =  defineStore('main',{
    state:()=>{
        return  {
            connt : 100,
            foo:0,
            arr:[1,2,3]
        }
    },
    getters:{
        // count10(state){
        //     console.log('调用了');
        //     return state.connt + 10
        // }
        // 如果在getters中使用this 则必须手动指定返回值的类型,否则类型推导不出来
        count10() : number{
            console.log('调用了');
            return this.connt + 10
        }
    },
    actions:{
            changeState(num : number){
            this.connt+=num
            this.foo = 23
            this.arr.push(4)
            // 方式 二 ,方式三都可以在这里使用
            // console.log(this);
            // this.$patch(state=>{
            //     this.connt++
            //     this.foo = 23
            //     this.arr.push(4)
            // })
        }
    }
})
// 2 使用容器中的 state

// 3.修改state

// 4 容器中的action的使用

(3)在需要使用 pinia 的文件中


<template>
 <div>{{myPinia.$state.connt}}</div>
 <hr>
 <div>{{foo}}</div>
 <button @click="deitlist">修改数据</button>


</template>

import { $ref,$ } from "vue/macros";

import {  myPiniastate } from '../store'
const myPinia = myPiniastate()
console.log(myPinia.$state.connt);
//也可以这样 (但是这样是有问题的,因为这样拿到的数据不是响应式的)
//pinia 其实就是把state数据都做了reactive处理了

const {foo} = $(storeToRefs(myPiniastate()))
console.log(foo);



const deitlist = ()=>{
    // 方式一: 数据修改 最简单的方式
  myPinia.$state.connt++

 // 方式二: 修改多个数据,建议使用$path批量更新
myPiniastate().$patch({
  foo: 23,
  connt: myPiniastate().$state.connt + 1,
});
// 方式三: $patch 一个函数,批量更新
 myPiniastate().$patch((stare)=>{
stare.connt++
stare.foo = 123
stare.arr.push(4)
 })
 // 方式四: 逻辑比较复杂的时候可以封装到actions做处理
  myPiniastate().changeState(10)
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值