pinia的模块划分
pinia 的模块划分是通过 js 命名来划分的。
示例:
第一步:拆分 store 文件
- store/index.ts
创建一个store对象,并导出
import { createPinia } from "pinia"
const store = createPinia()
export default store
- store/user.ts
用户store
import {defineStore} from "pinia"
export const useUserStore = defineStore({ //js命名
id: "user",
state: () => {
return {
name: '张三',
age: 18
}
}
})
- store/order.ts
订单store
import {defineStore} from "pinia"
export const useOrderStore = defineStore({ //js命名
id: "order",
state: () => {
return {
orderList: [{id: 1001, total: 6666}, {id: 1002, total: 8888}, {id: 1003, total: 9999}]
}
}
})
第二步:vue
- User.vue
使用用户store
<template>
User:{{ name }} == {{ age }}
</template>
<script setup lang="ts">
import {storeToRefs} from "pinia"
import {useUserStore} from "@/store/module/user"
const userStore = useUserStore()
const {name, age} = storeToRefs(userStore)
</script>
- Order.vue
使用订单store
<template>
order <br>
{{order}}
</template>
<script setup lang='ts'>
import {storeToRefs} from "pinia"
import {useOrderStore} from "@/store/module/order"
const orderStore = useOrderStore()
const order = storeToRefs(orderStore)
</script>
原文地址 blog.csdn.net