1 pinia 的理解
在 vue 2.x 中,vuex是官方的状态管理库,并且 vue3 中也有对应的 vuex 版本。个人认为Pinia语法更加简洁,不必像 vuex 那样定义 state、mutations、actions、getters 等,实现了API 等方式返回状态和改变状态的方法。
同时它支持 vuex 中 state、actions、getters 形式的写法,丢弃了 mutations,抛弃了vuex中的异步要求,开发时候不再根据同步异步来决定使用 mutations 或 actions,pinia 中只有 actions,极大简化了开发流程。同时对于对TypeScript 支持非常友好。
2 pinia 的使用
2.1安装Pinia
// 使用 yarn 或者 使用 npm
yarn add pinia;
npm i pinia;
2.1创建 pinia 实例(根存储 root store)
import type { App } from 'vue'
import { createPinia } from 'pinia'
import useUserStore from './modules/users'
// 创建store
const store = createPinia()
// 用于在main.js中注册
export function registerStore( app: App ) {
app.use( store )
}
// 导出可在vue页面中进行使用
export { useUserStore }
// 全部整个store
export default store;
2.2在 main.ts 中以插件的方式传递给 App 实例
import pinia from '@/store'
app.use(pinia)
2.3 模块的创建
import user from './user'
import keepAlive from './keepAlive'
const store = {}
export const registerStore = () => {
store.user = user()
store.keepAlive = keepAlive()
}
export default store
// 想要使用必须先引入 defineStore;
import { defineStore } from 'pinia';
// defineStore 方法有两个参数,第一个参数是模块化名字(也就相当于身份证一样,不能重复 id)
// 第二个参数是选项,对象里面有三个属性,相比于vuex 少了一个 mutations.
export const useStore = defineStore('main', {
state(){ // 存放的就是模块的变量
return {
count: 10
}
},
getters:{ // 相当于vue里面的计算属性,可以缓存数据
},
actions:{ // 可以通过actions 方法,改变 state 里面的值。
}
})
2.4 数据页面的使用
<template>
<div>
<p>{{store.count}}</p>
</div>
</template>
<script>
// 这里引入我们导出的 useStore;
import { useStore } from '../store/index.js'
export default {
setup(props) {
// useStore 是一个方法,调用之后会给我们返回一个对象。
// 这个时候,你就会发现,页面上就能正常显示我们在index.js 里面的 state 里面定义的 count 数据。
const store = useStore();
return {
store
}
}
}
</script>
2.5 修改 state 状态的方法。
// html 代码
<p>{{count}}</p>
<button @click="add">累计</button>
// js 代码
const store = useStore();
const add = () => {
store.count ++
}
2.6 actions 修改数据
// 首先我们需要在 actions 里面定义一个方法
import { defineStore } from 'pinia';
export const useStore = defineStore('main', {
state(){
return {
count: 10,
num: 20
}
},
getters:{
},
actions:{
piniaAdd(){
this.count++;
}
}
})
// 页面
// html 代码
<p>我是count数据{{count}}</p>
<p>num{{num}}</p>
<button @click="add">计数</button>
// js代码
const store = useStore();
const add = () => {
store.piniaAdd();
}