个人技术分享

安装

npm install pinia

在 main.js 中注册

// main.js

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

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

创建 store

// stores/counter.js

import { defineStore } from "pinia";

export const useCounterStore = defineStore("counter", {
  state: () => ({
    count: 0,
  }),
  getters: {	// 类似计算属性,基于store中的状态进行动态计算。当它们所依赖的state发生变化时,getters会自动更新其返回值。
    double: (state) => {	
      return state.count * 2;
    },
  },
  actions: {
    increase() {
      this.count++;
    },
  },
});

使用 store

<!-- Counter.vue -->

<script setup>
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia'

const counter = useCounterStore();
const { count, double } = storeToRefs(counter);		// 将store中的结构数据转为响应式的ref对象
</script>

<template>
  <button @click="counter.increase">{{ count }} - {{ double }}</button>
<template>