一、安装
npm install pinia
二、main.ts引入
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
const app = createApp(App)
app.use(createPinia())
app.mount('#app')
三、定义参数
import { defineStore } from 'pinia'
type User = {
name: string,
age: number
}
const peo: User = {
name: 'cqs',
age: 23
}
const login = (): Promise<User> => {
return new Promise(resolve => {
setTimeout(() => {
resolve(peo)
}, 2000)
})
}
export const useTestStore = defineStore('user', {
state: () => {
return {
name: 'cqs',
age: 23,
user: <User>{}
}
},
getters: {
getNewName():string {
return `好名字:${this.name}-${this.getAge}`
},
getAge():number {
return this.age
}
},
actions: {
setName(name: string) {
this.name = name;
},
async setUser() {
const user = await login()
this.user = user
}
}
})
四、store使用
1.直接获取
<script setup lang="ts">
import { useTestStore } from '../store'
const user = useTestStore();
console.log(user.age)
</script>
2.通过storeToRefs 获取
<script setup lang="ts">
import { storeToRefs } from 'pinia'
const { name, age } = storeToRefs(user)
</script>
3.$patch修改
<script setup lang="ts">
import { useTestStore } from '../store'
const user = useTestStore();
user.$patch({
name: '123'
})
user.$patch((state)=>{
state.name = '456'
})
</script>
4.直接修改
<script setup lang="ts">
import { useTestStore } from '../store'
const user = useTestStore();
user.name = '123'
</script>
5.通过$state修改
<script setup lang="ts">
import { useTestStore } from '../store'
const user = useTestStore();
//重写需要参数都传
user.$state = {
name: 'qwe',
age: 234,
user: {
name: '123',
age: 23
}
}
</script>
五、回滚数据
<script setup lang="ts">
import { useTestStore } from '../store'
const user = useTestStore();
user.$reset()
</script>
六、监听数据变化
<script setup lang="ts">
import { useTestStore } from '../store'
const user = useTestStore();
//监听数据改变
user.$subscribe((args, state)=>{
console.log(args);
console.log(state);
}, {
detached: true, //页面销毁,方法不会销毁
deep: true,
flush: 'post'
})
//监听调用actions,第二个参数true页面销毁,方法不会销毁
user.$onAction((args)=>{
args.after(()=>{
console.log('监听调用数据改变之后');
})
console.log(args);
}, true)
</script>
七、添加浏览器缓存,避免刷新页面数据消失
修改main.ts
import { createApp, toRaw } from 'vue'
import App from './App.vue'
import { createPinia, PiniaPluginContext } from 'pinia'
const app = createApp(App)
type Option = {
key: string
}
const PiniaPlugin = (option: Option) => {
return (context: PiniaPluginContext) => {
const { store } = context;
const data = localStorage.getItem('pinia-' + option.key + store.$id);
store.$subscribe(() => {
localStorage.setItem('pinia-' + option.key + store.$id, JSON.stringify(toRaw(store.$state)))
})
return {
...(data ? JSON.parse(data) : {})
}
}
}
const store = createPinia();
store.use(PiniaPlugin({ key: 'cqs' }))
app.use(store)
app.mount('#app')