pina基本使用

279 阅读1分钟

什么是 Pinia

Pinia 是 Vue 的最新 状态管理工具 ,是 Vuex 的 替代品

  1. 提供更加简单的 API (去掉了 mutation )
  2. 提供符合,组合式风格的 API (和 Vue3 新语法统一)
  3. 去掉了 modules 的概念,每一个 store 都是一个独立的模块
  4. 配合 TypeScript 更加友好,提供可靠的类型推断

Pinia用法

使用包管理器安装 Pinia

yarn add pinia // 或者使用npm npm install pinia

导入Pinia

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia() // 创建Pinia实例

createApp(App).use(pinia).mount('#app')


如何使用

①第一种:与Vue的选项式API类似,我们也可以传入一个带有state、actions与getters属性的Option 对象

// 定义store
// 语法:defineStore(仓库的唯一标识,() => { ... })
import { defineStore } from "pinia";
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
    increment2() {
      setTimeout(() => {
        this.count += 2;
      }, 1000);
    },
  },
})

  • state 是 store 的数据 (data)
  • getters 是 store 的计算属性 (computed),
  • actions 则是方法 (methods)。

②也存在另一种定义 store 的可用语法。与 Vue 组合式 API 的 setup 函数 相似,我们可以传入一个函数,该函数定义了一些响应式属性和方法,并且返回一个带有我们想暴露出去的属性和方法的对象。

import { defineStore } from "pinia";
import { ref, computed } from "vue";
export const useCounterStore = defineStore("counter", () => {
  const count = ref(0);
  const doubleCount = computed(() => count.value * 2);
  function addCount() {
    count.value++;
  }
  function addCount2() {
    setTimeout(() => {
      count.value += 2;
    }, 1000);
  }
  return { count, doubleCount, addCount, addCount2 };
});

在 Setup Store 中:

  • ref() 就是 state 属性
  • computed() 就是 getters
  • function() 就是 actions

示例

*(第一种)

<template>
  <button @click="store.increment">点击加一</button>
  <button @click="store.increment2">异步加二</button>
  <h2>{{ store.count }}</h2>
  <h2>{{ store.doubleCount }}</h2>
</template>

<script setup>
import { useCounterStore } from "./store/index.js";
let store = useCounterStore();
</script>

*(第二种)

<template>
  <button @click="store.addCount">点击加一</button>
  <button @click="store.addCount2">异步加二</button>
  <h2>{{ store.count }}</h2>
  <h2>{{ store.doubleCount }}</h2>
</template>

<script setup>
import { useCounterStore } from "./store/index.js";
let store = useCounterStore();
</script>