pinia介紹與使用


介紹

官方文檔
Pinia是Vue生態里Vuex的代替者,一個全新Vue的狀態管理庫,語法更加簡潔;在推出vue3后,強烈推薦使用pinia代替vuex,因為它支持Composition api 和 對TypesScript的完美支持。

安裝

npm install pinia
image

項目中引入Pinia

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

新建Store

在src的根目錄下新建 store\index.ts

import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
    state:()=>{
        return {
            count: 0,
            status: true
        }
    },
    getters:{},
    actions:{}
})

改變pinia的狀態數據

使用storeToRefs( )會對結構的數據處理起到響應式的效果

<script setup lang="ts">
    import { storeToRefs } from "pinia";
    import { useStore } from '../store/index'
    const user = useStore();
	//storeToRefs
    const { count, status } = storeToRefs(user);

    const handClick=()=>{
        user.count++
    }

</script>

<template>
<h3>{{count}}</h3>
<button @click="handClick">增加</button>
</template>

使用$path 修改多條狀態數據

<script setup lang="ts">
    import { useStore } from '../store/index'
    const user = useStore();

    const handClick=()=>{
    user.$patch((state)=>{
            {
            state.status = user.count > 10 ? false : true,
            state.count = user.status ? user.count+1:user.count-1
        }
        })
    }
</script>

Actions 通過函數更改狀態

在store\index文件中actions函數中添加changeState()方法,然后再組件中通過store直接調用

// store\index.ts
import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
    state:()=>{
        return {
            count: 0,
            status: true
        }
    },
    getters:{},
    actions:{
        changeState(){
            this.count++;
        }
    }
})

// 組件中通過store直接調用
<script setup lang="ts">
    import { useStore } from '../store/index'
    const user = useStore();

    const handClick=()=>{
        user.changeState()
    }
</script>

Getters類似vuex的計算屬性

手機號碼中間四位顯示*號
在store\index文件中Getters函數中添加phoneHidden()方法,然后再組件中通過store直接調用

//在store\index
import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
    state:()=>{
        return {
            count: 0,
            status: true,
            phone: '15898970112'
        }
    },
	// getters
    getters:{
        phoneHidden(state){
            return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
        } 
    },
    actions:{
        changeState(){
            this.count++;
        }
    }
})
//組件中
<h3>電話號碼{{user.phoneHidden}}</h3>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM