vue3之pinia 初始

154 阅读1分钟

1.Pinia简介

Pinia是Vue的存储库,和Vuex状态管理类似;但是与Vuex相比,Pinia提供了更简单的API,应用更加简单

2.项目中配置和使用Pinia

  • 创建一个Vue3项目
  • 安装Pinia npm install pinia --save
  • 项目中导入Pinia
//main.js文件
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import {createStore} from "pinia"

createApp(App).use(router).use(createStore()).mount('#app')
  • 创建store仓库 项目根目录下创建store文件夹,新建counter.js文件
//分布式
import {defineStore} from "pinia"
//useNumStore:use+关键词+Store
//defineStore: 参数1:参数名 参数2:对象
export const useNumStore = defineStore("num",{
    state:()=>{
        return{
            count:1321321
        }
    }
})
//组合式
import {defineStore} from "pinia"
import {ref} from "vue"
export const useNumStore = defineStore("num",()=>{
    const count = ref(1213123)
    return {
        count
    }
})
  • 在组件中使用
<template>
  <div>
    <p>Num的值为:{{store.count}}</p>
  </div>
</template>

<script setup>
import {useNumStore} from "../store/counter"

const store = useNumStore()
</script>

image.png

  • 改变Count的值
<template>
  <div>
    <p>Num的值为:{{store.count}}</p>
   <button @click="addHander">增加</button>
   <button @click="delHander">减少</button>
  </div>
</template>

<script setup>
import {useNumStore} from "../store/counter"
const store = useNumStore()
function addHander(){
  store.count++
  console.log("增加--->" + store.count)
}
function delHander(){
  store.count--
  console.log("减少--->" + store.count)
}
</script>

控制台打印结果

image.png

  • Getters --- 等同于Store状态的计算值

注意:getters 里要用箭头函数,否则在使用的时候读取不到(暂时不知道为啥)

store/counter.js
import {defineStore} from "pinia"
export const useNumStore = defineStore("num",{
    state:()=>{
        return{
            count:10
        }
    },
    getters:{
        getCount:(state)=>"当前Count的值为:" + state.count
    }
})
<template>
  <div>
    <p>Num的值为:{{store.count}}</p>
    <p>{{ store.getCount}}</p>
   <button @click="addHander">增加</button>
   <button @click="delHander">减少</button>
  </div>
</template>
  • Actions --- 等同于methods
store/counter.js
import {defineStore} from "pinia"

export const useNumStore = defineStore("num",{
    state:()=>{
        return{
            count:10
        }
    },
    getters:{
        getCount:(state)=>"当前Count的值为:" + state.count
    },
    actions:{
        addCount(){
            this.count+=2
        },
        delCount(){
            this.count-=2
        }
    }
})

在组件中使用

function addHander(){
  store.addCount();
}
function delHander(){
  store.delCount();
}

待更新...