在vue3.2.x 版本中引入 pinia (状态管理) 大菠萝

797 阅读1分钟

大家好,我是muddyrain,一个前端小🔥,热爱前端以及热爱开发.

Pinia - vue的状态存储库,如果你熟练于使用 compositionAPi,那你一顶会热爱上它.

继之前我们构建的 vue3-cli 脚手架项目来写,如果需要了解下自己想要使用 webpack5搭建的话可以浏览下. webpack5-vue3-cli

废话不多说直接上代码:

1. 安装插件

npm install pinia -D

2.在注册use使用插件

打开之前在 src目录下注册的 index.js 文件并做修改

// src/index.js
// 使用 Tree Shaking 方式进行引入 - 目前比较流行的模块导入导出方式-可以减少不必要的引用代码占用大小
import { createApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";
// 这里我们只需要在后面进行 链式 use 去注册
createApp(App).use(createPinia()).mount("#app");

3. 创建 store

可以在与 index.js 同目录下创建一个 store/counter.js 来构建我们的状态

// 也是使用了 tree shaking 方式
import { defineStore } from "pinia";
// defineStore 第一个参数为 此状态的 id ,后面的就是此状态下面的配置了
export const useCounterStore = defineStore("counter", {
// 状态参数 我们可以像之前写 vue2 一样使用 return 方式来进行返回一个不被污染的对象
  state() {
    return {
      num: 1,
    };
  },
  actions: {
    add() {
      this.num++;
    },
  },
});

4. 如何使用

App.vue 我们的根组件进修编写

<script setup>
import { ref } from "vue";
// 引入过来
import { useCounterStore } from "./store/counter.js";
// 直接使用 hooks 方式进行调用 获取当前状态的属性
const counterStore = useCounterStore();
</script>

<template>
  
  {{ counterStore.num }}
  <button @click="counterStore.add">点击</button>
</template>

<style lang="scss">
body {
  background-image: url("./1.jpg");
}
</style>

结果就立马出来了:

2022-08-03 12-48-41.2022-08-03 12_48_58.gif

另外 pinia 也支持在 devTools 里进行查看状态值的.

2022-08-03 12-51-29.2022-08-03 12_52_17.gif

好了,pinia的简单使用就到这里了,这篇只是基础语法,后续再迭代下 Plugins 以及 在组件外部如何使用状态库,谢谢大家的阅读!