Actions(支持同步异步)
1.同步 直接调用
2.异步 可以结合async await 修饰
import { defineStore } from 'pinia'
type User = {
name:string,
age: number
}
let user:User = {
name: '小黑',
age: 18
}
export const useStore = defineStore('main', {
state:()=> {
return {
data: <User>{},
age: 18
}
},
getters: {
setName():string {
return `---${this.age}----${this.setAge}`
},
setAge():number {
return this.data.age
}
},
// actions 可以同步和异步
actions: {
setUser() {
this.data = user
}
}
})
<template>
<div>
{{ user.data }}
{{user.age}}
{{user.setName}}
<button @click="change">改变值</button>
</div>
</template>
<script setup lang="ts">
import { useStore } from "./store"
const user = useStore();
const change = () => {
user.setUser()
}
</script>
<style scoped></style>