安装Pinia包
npm install pinia
main.js注册Pinia
import {
createPinia } from "pinia";
const app = createApp(App)
const pinia = createPinia();
app.use(pinia);
在src下创建store/store.js文件,放入以下内容
import {
defineStore } from "pinia";
// 导出方法(每个方法对应一个模块,相当于vuex的模块化,引入组件时按需引入)
export const xj = defineStore("main", {
state: () => {
return {
name: "萧寂",
age: 22,
sex: "男",
};
},
getters: {
getAddAge: (state) => {
// 传参在返回的函数写传入的参数
return (num) => state.age + num;
},
// 在getter里面调用其他的getter使用this
getNameAndAge() {
return this.name + this.getAddAge(10); // 调用其它getter
},
},
actions: {
saveName(name) {
//访问state里面的数据使用this.
setTimeout(() => {
this.name = name;
}, 1000);
},
},
});
在app.vue中的使用(在其他组件也一样的)
<script setup>
//解构出store.js内的需要的方法(每个方法对应一个模块,相当于vuex的模块化)
import {
xj } from "./store/store";
//将数据变成响应式的方法
import {
storeToRefs } from "pinia";
// 调用解构出来的方法
const store = xj();
//将store内的属性变成响应式的
storeToRefs(store);
//也可以(二者使用方式等价)
// const {name,age} = storeToRefs(store); //此时的name和age也是响应式的,但和ref不同,修改name或者age需要用store调用,如store.name=''
//修改数据
const changeName = () => {
store.name = "张三";
};
//还原/重置所有数据
const reasetName = () => {
store.$reset();
};
//批量修改数据
const pathStore = () => {
store.$patch({
name: "小红",
age: 50,
});
};
//
const channame = () => {
store.saveName("二哈");
};
</script>
<template>
<div class="">{
{ store.name }}</div>
<div>年龄: {
{ store.age }}</div>
<!-- 访问store里面的getters方法 -->
<p>getters返回的新年龄---{
{ store.getAddAge(50) }}</p>
<p>调用其它getter:{
{ store.getNameAndAge }}</p>
<button @click="changeName">更改姓名</button>
<button @click="reasetName">重置/还原姓名</button>
<button @click="pathStore">批量修改数据</button>
<button @click="channame">调用actions的方法一秒后改变姓名</button>
</template>
<style scoped lang="scss"></style>
接下来直接运行就好