跳转到主要内容
冬月的博客

pinia 是什么

pinia 是一个vue 的状态管理库

pinia 如何安装

npm install pinia

pinia 如何使用

先在mian.js中引入pinia

import { createApp } from "vue";
import App from "./App.vue";
import { createPinia } from "pinia";

const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount("#app");

创建一个store

在src\stores\counter.js创建一个store

import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCounterStore = defineStore('counter',()=> {
    // 定义数据
    const count = ref(0);

    // 定义修改数据的方法
    const increment = () => {
        count.value++;
    }
    // 一对象的方式return供组件使用
    return {
        count,
        increment
    }
})

在组件中使用store

<script setup>
// 1.导入 use打头的方法
import { useCounterStore } from '@/stores/counter'
// 2.执行方法得到store实例对象
const counterStore = useCounterStore()
// 3.使用store实例对象
console.log(counterStore)
</script>

<template>
  <button @click="counterStore.increment">{{ counterStore.count }}</button>
</template>

<style scoped></style>

思路解析

graph TD
    1[先在main里导入pinia]
    2[在src\stores\counter.js创建一个store]
    3[在组件中使用store]
    1 --> 2 --> 3