pinia新的状态管理工具
1、安装
npm install pinia --save
2、新建store,在main.js中引入
在根目录下新建store文件夹,新建index.js
import { createPinia } from "pinia";
// 创建store
const store = createPinia();
export default store;
main.js
import { createApp } from "vue";
import App from "./App.vue";
import store from "./store";
const app = createApp(App);
app.use(store);
app.mount("#app");
3、在store文件夹下新建stateStore.js
import { defineStore } from "pinia";
export const stateStore = defineStore({
id: "state", //命名
state: () => {
return {
name: "菠萝",
age: 99,
};
},
//会缓存,不改变不调用,像计算属性
getters: {
getterName(state) {
console.log("使用了getter");
return "我是什么水果?我是" + state.name;
},
},
actions: {
//还支持调用别的actions
updateName(name, age) {
this.name = name;
this.updateAge(age);
},
updateAge(age) {
this.age = age;
},
//异步action 也支持 async/await的语法
async asyncfun() {
const timer = setTimeout(() => {
this.name = "桃子";
}, 1000);
await timer;
},
},
});
4、使用
先引入创建的store
解构需要引入storeToRefs
修改state数据可以直接修改,也可以使用$patch
,也可以使用actions
修改
<template>
<div>
<h1>pinia:{{ name }}</h1>
<h1>pinia:{{ age }}</h1>
<h1>pinia.getter:{{ state.getterName }}</h1>
<el-button type="primary" @click="changeName">修改pinia</el-button>
</div>
</template>
<script setup>
import { stateStore } from "../store/state";
//解构store
import { storeToRefs } from "pinia";
const state = stateStore();
const { age, name } = storeToRefs(state);
const changeName = () => {
// 通过patch修改数据两种方式对象和函数
// 1、对象
// state.$patch({
// name: "西瓜",
// age: 100,
// });
// 2、函数
// state.$patch((state) => {
// state.name = "哈密瓜";
// state.age = 999;
// });
// 通过action修改数据
state.updateName("香蕉", 88);
state.asyncfun();
};
</script>
<style lang="less" scoped></style>