Vue3使用pinia


在这里插入图片描述

Pinia

pinia是全局状态管理库,具有一下特点

  • 完整的ts支持
  • 体积小
  • 去除mutations,使用方便
  • actions支持同步和异步
  • 支持vue3和vue2

安装


npm install pinia

引入注册

import { createApp } from 'vue'
import App from './App.vue'
import {createPinia} from 'pinia'
 
const store = createPinia()
let app = createApp(App)
 
 
app.use(store)
 
app.mount('#app')

使用

1. 新建文件夹store

2. 新建index.ts

新建store-name.ts

export const enum Names {
    Test = 'TEST'
}
import {defineStore} from "pinia";
import {Names} from './store-name.ts'
export const useTestStore = defineStore(Names.TEST,{
    state:()=>{
        return {
            current:1,
            name:'熏悟空'
        }
    },
    //computed
    getters:{

    },
    //methods 可以同步或异步更新state
    actions:{
        setCurrent(num:number){
            this.current = num
        }
    }

})

3. Vue组件中使用

<template>
  <div>
    pinia: {{Test.current}} -- {{Test.name}}
    <button @click="change">change</button>
  </div>
</template>

<script setup lang=ts>
import {useTestStore} from "@/store";

const Test = useTestStore();

/**
 * 修改state值的方式
 * 1, Test.current++
 * 2, Test$patch({name:"唐僧"})
 * 3. Test.$patch((state) => {state.name="唐僧"})
 * 4. Test.$state = {current:2000,name:"唐僧"}
 * 5. 通过actions修改state
 */
const change = ()=>{
  Test.setCurrent(123)
}
</script>

<style scoped>
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值