export const useCartStore = defineStore('cart', () => {
const user = useUserStore()
+ const list = ref([])
const summary = computed(() => {
- return `Hi ${user.name}, you have ${state.list.length} items in your cart. It costs ${state.price}.`
+ return `Hi ${user.name}, you have ${list.value.length} items in your cart. It costs ${price.value}.`
})
function purchase() {
export const useCartStore = defineStore('cart', () => {
const user = useUserStore()
+ const list = ref([])
const summary = computed(() => {
- return `Hi ${user.name}, you have ${state.list.length} items in your cart. It costs ${state.price}.`
+ return `Hi ${user.name}, you have ${list.value.length} items in your cart. It costs ${price.value}.`
})
function purchase() {
```vue
<script setup>
const someStore = useSomeStore()
-// 该订阅器将被保留,即使组件被卸载
+// 此订阅器即便在组件卸载之后仍会被保留
someStore.$onAction(callback, true)
</script>
```
```vue
<script setup>
import { useCounterStore } from '@/stores/counter'
-// å\9c¨ç»\84ä»¶ç\9a\84ä»»ä½\95å\9c°æ\96¹访问 `store` 变量 ✨
+// å\8f¯ä»¥å\9c¨ç»\84ä»¶ä¸ç\9a\84ä»»æ\84\8fä½\8dç½®访问 `store` 变量 ✨
const store = useCounterStore()
</script>
```
```vue
<script setup>
const store = useCounterStore()
-// ❌ 这样是不可行的,因为它会破坏响应性
-// 就与直接解构 `props` 一样
+// ❌ 这将不起作用,因为它破坏了响应性
+// 这就和直接解构 `props` 一样
const { name, doubleCount } = store // [!code warning]
name // 将始终是 "Eduardo" // [!code warning]
doubleCount // 将始终是 0 // [!code warning]
<script setup>
import { storeToRefs } from 'pinia'
const store = useCounterStore()
-// `name` 和 `doubleCount` 都是响应式的 ref
-// 这也会提取插件添加的 ref 属性
-// 但会跳过任何 action 或非响应式(非 ref/reactive)属性
+// `name` 和 `doubleCount` 是响应式的 ref
+// 同时通过插件添加的属性也会被提取为 ref
+// 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
const { name, doubleCount } = storeToRefs(store)
// 作为 action 的 increment 可以直接解构
const { increment } = store
const store = useStore()
router.beforeEach((to, from, next) => {
- // 我们想用这里的 store
+ // 我们想要在这里使用 store
if (store.isLoggedIn) next()
else next('/login')
})
router.beforeEach((to) => {
- // ✅ 这样做是可行的,因为路由器在安装完之后就会开始导航。
- // Pinia 也将被安装。
+ // ✅ 这样做是可行的,因为路由器是在其被安装之后开始导航的,
+ // 而此时 Pinia 也已经被安装。
const store = useStore()
if (to.meta.requiresAuth && !store.isLoggedIn) return '/login'
### 添加新的 state %{#adding-new-state}%
-如果你想给 store 添加新的 state 属性,或者在激活过程中使用的属性,**你必须同时在两个地方添加它**。
+如果你想给 store 添加新的 state 属性或者在服务端渲染的激活过程中使用的属性,**你必须同时在两个地方添加它**。。
- 在 `store` 上,然后你才可以用 `store.myState` 访问它。
- 在 `store.$state` 上,然后你才可以在 devtools 中使用它,并且,**在 SSR 时被正确序列化(serialized)**。
```vue
<script setup>
const someStore = useSomeStore()
-// 该订阅器将被保留,即使组件被卸载
+// 此订阅器即便在组件卸载之后仍会被保留
someStore.$subscribe(callback, { detached: true })
</script>
```