Vue使用Pinia状态管理工具

264 阅读2分钟

Vue 使用 Pinia 状态管理工具 16/100 发布文章 ZTAHNG 未选择任何文件 new

全局状态管理工具

官方文档Pinia

在这里插入图片描述 Pinia.js 有如下特点:

  • 完整的 ts 的支持;
  • 足够轻量,压缩后的体积只有 1kb 左右;
  • 去除 mutations,只有 state,getters,actions;
  • actions 支持同步和异步;
  • 代码扁平化没有模块嵌套,只有 store 的概念,store 之间可以自由使用,每一个 store 都是独立的
  • 无需手动添加 store,store 一旦创建便会自动添加;
  • 支持 Vue3 和 Vue2

安装

yarn add pinia npm install pinia

Vue3 使用

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

const store = createPinia();
let app = createApp(App);

app.use(store);

app.mount("#app");

Vue2 使用

import { createPinia, PiniaVuePlugin } from "pinia";

Vue.use(PiniaVuePlugin);
const pinia = createPinia();

new Vue({
  el: "#app",
  // other options...
  // ...
  // note the same `pinia` instance can be used across multiple Vue apps on
  // the same page
  pinia,
});

文章来自非常优秀的京东大佬这是他的博客和他的教学资源 全局状态管理工具 官方文档 Pinia

在这里插入图片描述 Pinia.js 有如下特点:

完整的 ts 的支持; 足够轻量,压缩后的体积只有 1kb 左右; 去除 mutations,只有 state,getters,actions; actions 支持同步和异步; 代码扁平化没有模块嵌套,只有 store 的概念,store 之间可以自由使用,每一个 store 都是独立的 无需手动添加 store,store 一旦创建便会自动添加; 支持 Vue3 和 Vue2 安装 yarn add pinia npm install pinia

Vue3 使用 import { createApp } from 'vue' import App from './App.vue' import {createPinia} from 'pinia'

const store = createPinia() let app = createApp(App)

app.use(store)

app.mount('#app') Vue2 使用 import { createPinia, PiniaVuePlugin } from 'pinia'

Vue.use(PiniaVuePlugin) const pinia = createPinia()

new Vue({ el: '#app', // other options... // ... // note the same pinia instance can be used across multiple Vue apps on // the same page pinia, }) 文章来自非常优秀的京东大佬这是他的博客和他的教学资源

Markdown 899 字数 53 行数 当前行 1, 当前列 0HTML 635 字数 34 段落