Vue3-pinia (state management)

This is  vue3 a new state management tool. Simply put, it is equivalent to the previous one  vuex. It is removed  Mutations but it is still supported  vue2 . It is especially recommended. Because its logo looks like a pineapple, we also call it Big Pineapple.

 Official website   https://pinia.vuejs.org/

 install command

npm i pinia

  use

1, mian.js imported  pinia, global registration

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

const app = createApp(App)
app.use(createPinia())
app.mount('#app')

 2. Create a new file in the store folder  index.js , you can create it if you support TS  index.ts, and import it into the file  pinia to store the state

import {defineStore} from 'pinia'

export const useUserStore = defineStore("USER",{
    state() {
        return {
            name: '景天',
            age: 18,
            name1: '胡歌',
            age1: 36
        }
    },
    // 和vuex一样
    getters: {

    },
    // 和vuex一样
    actions: {
        setAge() {
            this.age--
        }
    }
})

3.  pinia The state stored in use in the page

<template>
    <div>正常取值</div>
    <div>{
   
   {User.name}}</div>
    <div>{
   
   {User.age}}</div>
    <div>解构取值</div>
    <div>{
   
   {name}}</div>
    <div>{
   
   {age}}</div>
    <div>解构取值转ref</div>
    <div>{
   
   {name1}}</div>
    <div>{
   
   {age1}}</div>
    <button @click="change1">change1</button>
    <button @click="change2">change2</button>
    <button @click="change3">change3</button>
    <button @click="change4">change4</button>
    <button @click="change5">change5</button>
    <div>
        <button @click="handleReset">重置</button>
    </div>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { useUserStore } from './store';

// 获取store中的值
let User = useUserStore()

// 通过ES6的结构取值,但是这个值不是响应式的
let {name,age} = User

// 通过pinia自带的方法,转换成ref,就是响应式的了
let {name1,age1} = storeToRefs(User)

// 改变store中值的方式有五种
// 方式一
function change1() {
    User.age++
}
// 方式二,可一次性修改多个值,对象的形式
function change2() {
    User.$patch({
        name: '雪见',
        age: 17
    })
}
// 方式三,可一次性修改多个值,函数的形式
function change3() {
    User.$patch((state) => {
        state.name = '徐长卿'
        state.age = 19
    })
}
// 方式四,哪怕修改一个值,也要传所有值???
function change4() {
    User.$state = {
        name: '茂茂',
        age: 16,
        name1: '李逍遥',
        age1: 18
    }
}
// 方式五,借助actions
function change5() {
    User.setAge()
    //也可以传参
    // User.setAge(999)
}

// 重置数据
function handleReset() {
    User.$reset()
}

</script>

<style>
</style>

Guess you like

Origin blog.csdn.net/QQ_Empire/article/details/126223602