Pinia是一个全新的Vue状态管理库,是Vuex的代替者,尤雨溪强势推荐
- Vue2 和 Vue3 都能支持
- 抛弃传统的
Mutation
,只有state, getter
和action
,简化状态管理库 - 不需要嵌套模块,符合 Vue3 的 Composition api,让代码扁平化
- TypeScript支持
- 代码简介,很好的代码自动分割
安装Pinia:npm i pinia
挂载Pinia:main.js
import { createApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";
import router from "./router";
const app = createApp(App);
app.use(createPinia());
app.use(router);
app.mount("#app");
创建Store:store/pinia.js <pinia>
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter", {
state: () => {
return {
msg: "张三",
};
},
getters: {},
actions: {},
});
使用 <页面>
<template>
<div class="">
{{ msg }}
<button @click="handler">点我</button>
</div>
</template>
<script setup>
import { useCounterStore } from "../stores/pinia.js";
const store = useCounterStore();
</script>
pinia结构能拿到值但是不具备响应式 需要用:storeToRefs
// 组件
<template>
<div class="">
{{ msg }}
<button @click="handler">点我</button>
</div>
</template>
<script setup>
import { useCounterStore } from "../stores/pinia.js";
import { storeToRefs } from "pinia";
const { msg } = storeToRefs(useCounterStore());
onMounted(() => {});
const handler = () => {
msg = '李四'
// 结构时加上storeToRefs页面才响应
};
</script>
<style lang="scss" scoped></style>
$patch可以通过基础数据修改方式去修改多条数据,并且会加快修改速度
// 组件
<template>
<div class="">
{{ msg }}
<button @click="handler">点我</button>
</div>
</template>
<script setup>
import { useCounterStore } from "../stores/pinia.js";
import { storeToRefs } from "pinia";
const store = useCounterStore ()
onMounted(() => {});
const handler = () => {
store.$patch((state)=>{
//此处state就是pinia仓库中的state
})
};
</script>
通过actions修改——store.方法名()调用 pinia中可以使用this
//组件
<script setup>
import { useCounterStore } from "../stores/pinia.js";
const store = useCounterStore();
const initList = {
name: "张三",
age: 14,
};
onMounted(() => {});
const handler = () => {
// action pinia
store.changeState("111");
};
</script>
// pinia.js
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter", {
state: () => {
return {
msg: "张三",
};
},
getters: {},
actions: {
changeState(it) {
//it为传过来的111 也可传对象等
this.msg = "李四";
},
},
});
Pinia 中的 getter 和 Vue 中的计算属性几乎一样,在获取 State值之前做一些逻辑处理
getter 中的值有缓存特性,如果值没有改变,多次使用也只会调用一次
也可以用 this来替换State
// pinia.js
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter", {
state: () => {
return {
msg: "张三",
age: 10,
};
},
getters: {
// 定义(num) 组件调用getState时可以传参
getState:(state) => {
return (num) => state.age + num;
},
getNameAddState() {
return this.name + this.getState; //pinia中可以使用this调用其他getters
},
},
actions: {
changeState(it) {
this.msg = "李四";
},
},
});