


























yarn add pinia
# or
npm i pinia
import { createPinia } from 'pinia'
const Pinia = createPinia()
createApp(App).use(Pinia).mount('#app')
src/test.js
defineStore方法import { defineStore } from 'pinia'
命名规则:useXxxStore
defineStore( storeID , {state,actions,getters} )
参数1:store的唯一标识,也就是仓库名字
参数2:对象,可以在对象内提供state、actions、getters
const useTestStore = defineStore('test', {
// state是一个函数 在返回的对象中写数据
state: () => {
return {
name: 'liao',
website: 'https://liaooo.cn',
}
},
actions: {},
getters: {}
})
export default useTestStore
<script setup>
import useTestStore from './store/test'
const test = useTestStore()
</script>
<template>
{{ test.name }}
{{ test.website }}
</template>
Pinia中没有mutations,只有actions
...
actions: {
changeName(name) {
this.name = name
}
}
...
<script setup>
import useTestStore from './store'
const test = useTestStore()
// 执行actions中的方法
test.changeName('liaoliao')
</script>
...
getters: {
infoPage() {
return this.website + '/talking'
},
}
...
<template>
...
{{ test.infoPage }}
</template>
<script setup>
import useTestStore from './store'
const test = useTestStore()
...
</script>
直接解构store中的数据会导致数据丢失响应式特性
<script setup>
import useTestStore from './store'
const test = useTestStore()
// 解构出来的数据将不再是响应式的
const { name, website } = test
...
</script>
使用storeToRefs可以使解构出来的数据依旧是响应式的
<script setup>
// 从pinia中引入storeToRefs方法
import { storeToRefs } from 'pinia'
...
const { name, website } = storeToRefs(test)
...
</script>
根据项目复杂程度,有时候需要存储较多数据,可以定义多个store,最后统一用一个根store整合
src/store/user.js
import { defineStore } from 'pinia'
const useUserStore = defineStore('user', {})
export default useUserStore
新建······模块
src/store/index.js
// 导入所有store
import useUserStore from './user'
import use···Store from './···'
// 统一导出useStore()方法
export default function useStore() {
return {
user: useUserStore(),
···: use···Store()
}
}
<script setup>
import { storeToRefs } from 'pinia'
import useStore from './store'
// 解构user store
const { user } = useStore()
const { name, pwd } = storeToRefs(user)
</script>
store.$subscribe详见下一篇笔记
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。