1. 安装pinia
npm install pinia -D
2.挂载
import { createApp } from "vue";
import App from "./App.vue";
import { createPinia } from "pinia";
const pinia = createPinia();
const app = createApp(App);
app.use(pinia);
app.mount("#app");
2.定义及使用数据
- 定义数据–index.ts
import { defineStore } from "pinia";
export const mainStore = defineStore("main", {
state: () => {
return {
helloWord: "Hello World",
count: 0,
};
},
getters: {},
actions: {
changeState() {
this.count++;
this.helloWord = "path";
},
},
});
- 使用状态
<template>
<div>{{ store.helloWord }}</div>
<div>{{ store.count }}</div>
<div>{{ helloWord }}</div>
<div>{{ count }}</div>
</template>
<script setup lang='ts'>
import { mainStore } from "../store/index";
import { storeToRefs } from "pinia";
const store = mainStore();
const { helloWord, count } = storeToRefs(store)
</script>
<style scoped></style>
3. 四种修改状态方法
<template>
<div>
<button @click="handleClick">修改状态数据(1)</button>
<button @click="handleClickPath">修改状态数据(2-path)</button>
<button @click="handleClickMethod">修改状态数据(3-path)</button>
<button @click="handleClickActions">修改状态数据(4-actions)</button>
</div>
</template>
<script setup lang='ts'>
import { mainStore } from "../store/index";
const store = mainStore();
//第一种方式
const handleClick = () => {
store.count++
store.helloWord = store.helloWord === 'Hello World' ? "Path" : "Hello World"
}
//第二种方式$path 好处:多数据修改,官方宣称 有优化,比第一种方式快一点
const handleClickPath = () => {
store.$patch({
count: store.count + 2,
helloWord: store.helloWord === 'Hello World' ? "Path" : "Hello World"
})
}
//第三种方法$patch 传递函数 这种方式更适合处理 复杂业务处理逻辑
const handleClickMethod = () => {
store.$patch((state) => {
state.count++;
state.helloWord = state.helloWord === 'Hello World' ? "Path" : "Hello World";
});
}
//第四种,actions形式,直接在index.ts编写
const handleClickActions = () => {
store.changeState();//这里纯粹是为了记笔记
}
</script>
<style scoped></style>
4. pinia中的Getters使用
getters 类似vue中计算属性,有缓存功能
import { defineStore } from "pinia";
export const mainStore = defineStore("main", {
state: () => {
return {
helloWord: "Hello World",
count: 0,
phone: "13255683632",
};
},
getters: {
phoneHidden(): string {
console.log("getters 被调用了");
return this.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2"); //正则表达式
},
},
actions: {
changeState() {
this.count++;
this.helloWord = "path";
},
},
});
- 调用地方
<template>
<div>{{ store.helloWord }}</div>
<div>{{ store.count }}</div>
<div>{{ store.phoneHidden }}</div>
<hr />
<div>{{ helloWord }}</div>
<div>{{ count }}</div>
<div>{{ phoneHidden }}</div>
</template>
5. pinia中Store的相互调用
` 先引入 import { otherStore } from “./other”;
actions: {
changeState() {
this.count++;
this.helloWord = "path";
},
getList() {
console.log(otherStore().list);
},
},