- 使用vite创建好一个vue3项目,开发语言选择ts
- 使用 npm i pinia -s 安装最新版本的pinia 这里我的版本安装的是 2.1.4
1.在main中注册pinia
import { createApp, createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import { createPinia } from "pinia";
let app = createApp(App);
const store = createPinia();
app.use(store);
app.mount("#app");
2.在store中创建index.ts和store-name.ts文件
index.ts内容如下:
import { defineStore } from "pinia";
import { Names } from "./store-name";
export const useTestStore = defineStore(Names.TEST, {
state: () => {
return {
current: 1,
name: "不染-9732",
};
},
getters: {},
actions: {},
});
store-name.ts内容如下:
export const enum Names {
TEST = "TEST",
}
app.vue文件的内容如下:
<template>
<div>app.vue===>pinia:{{ Test.current }}--{{ Test.name }}</div>
</template>
<script setup lang="ts">
import { useTestStore } from "./store/index";
const Test = useTestStore();
</script>
页面输出如下内容则一次简单的pinia的调用完成
<template>
<div>app.vue===>pinia:{{ Test.current }}--{{ Test.name }}</div>
<button @click="change">修改值</button>
</template>
<script setup lang="ts">
import { useTestStore } from "./store/index";
const Test = useTestStore();
const change=()=>{
Test.current++
}
</script>
const change=()=>{
// Test.current++
Test.$patch({
current:9999,
name:'一刀!'
})
}
const change=()=>{
Test.$patch((state=>{
state.current=999999,
state.name='两刀'
}))
}
const change=()=>{
Test.$state={
current:66,
name:'非酋玩家'
}
}
修改store中的index.ts中内容如下
import { defineStore } from "pinia";
import { Names } from "./store-name";
export const useTestStore = defineStore(Names.TEST, {
state: () => {
return {
current: 1,
name: "不染-9732",
};
},
getters: {},
// methods 能够做同步,异步 提交state
actions: {
setCurrent(num:number) {
this.current = num;
},
setName(name:string) {
this.name = '土豪玩家';
},
},
});
完整的App.vue的内容如下:
<template>
<div>app.vue===>pinia:{{ Test.current }}--{{ Test.name }}</div>
<button @click="changeCurrent">修改值</button
><button @click="changeName">修改名字</button>
</template>
<script setup lang="ts">
import { useTestStore } from "./store/index";
const Test = useTestStore();
const changeCurrent = () => {
// Test.current++
// Test.$patch({
// current:9999,
// name:'一刀!'
// })
// Test.$patch((state=>{
// state.current=999999,
// state.name='两刀'
// }))
// Test.$state={
// current:66,
// name:'非酋玩家'
// }
Test.setCurrent(888888);
};
const changeName = () => {
Test.setName("土豪玩家");
};
</script>
<template>
<div>app.vue===>数值:{{ Test.current }} --名字:{{ Test.name }}</div>
<button @click="changeCurrent">修改值</button
><button @click="changeName">修改名字</button>
</template>
<script setup lang="ts">
import { useTestStore } from "./store/index";
const Test = useTestStore();
Test.$subscribe((args,state)=>{
// args 当前修改的数据
// state state中所有数据的值
console.log('args===>',args);
console.log('state===>',state);
})
const changeCurrent = () => {
Test.current++
};
const changeName = () => {
Test.setName("土豪玩家");
};
</script>