一、安装
yarn add pinia
# 或者使用 npm
npm install pinia
二、配置步骤
1.引入
// 在main.js引入
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import {createPinia} from 'pinia'
// 这里可以链式调用
createApp(App).use(createPinia()).mount('#app')
2.创建实例对象
// 在src下创建store/index.js
import { defineStore } from "pinia";
onst store = defineStore("main", {
state: () => {
return {
count: 10
};
},
getters: {},
// vuex这里只能进行异步操作,而这里同步异步都可以
actions: {
setCount:()=>{
// 这里的this可以拿到store里的state和getter
this.count = 20
}
},
// 与vuex相比,没有了mutation
});
export { store };
三、使用
1.$patch和store.值
访问和修改state里的数据
<script setup>
import { toRefs } from "vue";
import { store } from "./store";
import { storeToRefs } from "pinia";
// 创建实例
const store1 = store();
// 将数据变成响应式的
// 方式1:
// let { count } = toRefs(store1);
// 方式2:
let { count } = storeToRefs(store1);
const dianji = () => {
// [这种方式只能修改1个数据]
store1.count++;
store1.list.push({
name: "vivo",
price: 9999,
});
};
// 修改store仓库里面的数据 通过$patch修改
const patchclick = () => {
store1.list.push({
name: "oppo",
price: 6666,
});
// [这种可以修改多条数据](推荐下面函数式写法)
store1.$patch({
count: store1.count + 5,
list: store1.list,
});
};
// 函数式写法
const disanzhon = () => {
// 自带state加持
store1.$patch((state) => {
state.list.push({
name: "小米",
price: 6666,
});
});
};
</script>
<template>
<div>
<h1>商品数量:{{ store1.count }}</h1>
<h1>商品数量2:{{ count }}</h1>
<button @click="dianji">点击</button>
<button @click="patchclick">$patch修改</button>
<button @click="disanzhon">$patch函数式修改</button>
<ul>
<li v-for="(item, index) in store1.list" :key="index">
{{ item.name }}:{{ item.price }}
</li>
</ul>
</div>
</template>
<style scoped>
</style>
2.$reset()
重置state(回复到最开始的时候)
<script setup>
import { toRefs } from "vue";
import { store } from "./store";
import { storeToRefs } from "pinia";
// 创建实例
const store1 = store();
// 将数据变成响应式的
let { count } = storeToRefs(store1);
// 重置
const chonzhi = () => {
store1.$reset();
};
</script>
<template>
<div>
<button @click="chonzhi">重置</button>
</div>
</template>
<style scoped>
</style>
3.$subscribe
监听仓库变化
// 监听整个仓库变化
store1.$subscribe((mutation,state)=>{
// 数据变化的一些信息
console.log(mutation);
console.log(state);
})
4.使用actions里的方法
<button @click="store1.getTimu()">请求</button>