• 如何在Vue中使用Pinia进行状态管理
  • 发布于 2个月前
  • 193 热度
    0 评论
  • 阳光
  • 1 粉丝 29 篇博客
  •   
在前端Vue项目开发中,数据的跨组件状态在某些场景下是很有必要的,当你在一个SPA单页面的APP中需要一个全局变量的时候,Pinia是一个简单而又高效的选择。

安装Pinia
# 使用pnpm
pnpm i pinia

#或者使用 rarn
yarn add pinia

# 或者使用 npm
npm install pinia

main.js
在程序入口处引入pinia:
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import { createPinia } from 'pinia'
import router from "./router/index.js";

const pinia = createPinia()
const app = createApp(App)


app.use(pinia)
app.use(router)
app.mount('#app')

定义Store
首先在项目的src目录下,创建stores目录和index.js:
import { defineStore } from "pinia"
// 堆代码 duidaima.com
export const useTestStore = defineStore("Test",{
    state:()=>({
        count:0
    }),
    getters:{
        double:(state)=>state.count * 2,
    },
    actions : {
        add(){
            this.count ++
        },
    },
})
这里定义了一个state,你可以理解为项目中的全局变量,getters可以理解为Vue中的计算属性,actions可以理解为组件中的method。

使用state
这里我定义了两个页面,router/index.js:
import { createRouter,createWebHashHistory } from 'Vue-router'
import HomeView from "../views/HomeView.vue";
import TestView from "../views/TestView.vue";

const router = createRouter({
    history:createWebHashHistory(),
    routes:[
        {
            path:'/',
            name : 'home',
            component:HomeView
        },
        {
            path : '/test',
            name : 'test',
            component:TestView
        }
    ]

})
export default router;
通过上边的路由代码可以看出页面组件目录。

在这两个组件中,我使用了state:
<template>
<h1>Home Page</h1>
<div class="card">
    <button type="button" @click="store.add">count is {{ store }}</button>
</div>
</template>

<script setup>
import {useTestStore} from "../stores/index.js";

const store = useTestStore()
</script>

运行调试
我们启动服务器npm run dev,通过路由导航点击到home页面,点击按钮触发count增加的事件,可以观察按钮中store的属性值变化,当我们切换到test页面,发现store值并不是初始值,而是点击后增加的值,当在test页面点击按钮是,store的值也会增加,切换会home页面时,store保持不变,综合发现store可以跨组件共享变量,达到了全局变量的效果。

总结
pinia的使用简单方便功能强大,在定义不同的全局state是,可以分别创建不同的文件来区分,这下子再也不用Vue中变量全局共享发愁了。
用户评论