1. Pinia installation
command install
yarn add pinia
# or with npm
npm install pinia
2. Using Pinia
1. Import and mount main.js
import { createPinia } from 'pinia'
app.use(createPinia())
2. Build index.js under the store package
to write
import { defineStore } from 'pinia'
//1.定义并导出容器
//参数1:容器的ID.必须唯一,将来Pinia会把所有的容器挂载到根容器
//参数2:选项对象
//返回值:一个函数,调用得到容器实例
export const useStore = defineStore('storeId', {
/**
* 类似于组建的data,用来储存全局状态
* 1.必须是函数,这样为了在服务端渲染的时候避免交叉请求导致的数据状态太污染
* 2.必须是箭头函数,为了更好的TS类型推导
*/
state: () => {
return {
username:'张三',
phone:'1734985035',
createTime:'2004-05-12',
updateTime:'2023-01-04',
}
},
/**
* 类似于组件的computed,用来封装计算属性,有缓存的功能
*/
getters:{},
/**
* 类似于组建的methods,封装业务逻辑,修改state
*/
actions:{}
})
3. Then introduce the store in the page and use pinia.
<template>
<h3>pinia</h3>
<!-- 在页面中直接使用就可以了 -->
<p>pinia 中的信息: {
{store.username}} --- {
{store.phone}}</p>
<!-- 下面这种调用方法也可以 -->
<p>{
{createTime}}<p>
</template>
<script setup>
// 首先需要引入一下我们刚刚创建的store
import { useStore } from '../store';
// 因为是个方法,所以我们得调用一下
const store = useStore();
console.log(store)
let {username,phone,createTime,updateTime} = store
</script>
<style scoped>
</style>
The output information is as follows:
After the page is refreshed , the data will be reset. Install a pinia plugin like vuex-persistdstate to solve it.
3. Persistent storage
install plugin
npm install pinia-persistedstate-plugin
2. If the plug-in is placed globally, it is relatively poor to maintain, so make changes to the previous main.js and change it back to the reference store folder
import store from './store'
app.use(store)
The original store/ index.js is divided into user modules and renamed to user.js, and the content in store/index.js is changed
import { createPinia } from "pinia";
//引入插件
import { createPersistedState } from "pinia-persistedstate-plugin";
const store = createPinia();
//使用插件
store.use(createPersistedState());
export { store };
The difference between Vuex and Pinia:
Support optional api and combined api writing
Pinia has no mutations, only: state, getters, actions
The pinia sub-module does not require modules (the previous vuex sub-module required modules)
TypeScript support is good
Automated Code Splitting
pinia is smaller (better performance)
pinia can directly modify state data
References:
Pinia Simple Use Tutorial P22-24