```js
import { defineStore } from 'pinia'
-// 你可以任意命名 `defineStore()` 的返回值,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。
+// `defineStore()` 的返回值的命名是自由的
+// 但最好含有 store 的名字,且以 `use` 开头,以 `Store` 结尾。
// (比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useAlertsStore = defineStore('alerts', {
```js
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
+ const name = ref('Eduardo')
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
- return { count, doubleCount, increment }
+ return { count, name, doubleCount, increment }
})
```
```vue
<script setup>
import { useCounterStore } from '@/stores/counter'
-// å\8f¯ä»¥å\9c¨ç»\84ä»¶ä¸ç\9a\84ä»»æ\84\8fä½\8d置访é\97® `store` å\8f\98é\87\8f ✨
+// å\9c¨ç»\84ä»¶å\86\85é\83¨ç\9a\84ä»»ä½\95å\9c°æ\96¹å\9d\87å\8f¯ä»¥è®¿é\97®å\8f\98é\87\8f `store` ✨
const store = useCounterStore()
</script>
```
如果你还不会使用 `setup` 组件,[你也可以通过**映射辅助函数**来使用 Pinia](../cookbook/options-api.md)。
:::
-你可以定义任意多的 store,但为了让使用 pinia 的益处最大化 (比如允许构建工具自动进行代码分割以及 TypeScript 推断),**你应该在不同的文件中去定义 store**。
+你可以定义任意多的 store,但为了让使用 pinia 的益处最大化(比如允许构建工具自动进行代码分割以及 TypeScript 推断),**你应该在不同的文件中去定义 store**。
一旦 store 被实例化,你可以直接访问在 store 的 `state`、`getters` 和 `actions` 中定义的任何属性。我们将在后续章节继续了解这些细节,目前自动补全将帮助你使用相关属性。
import { computed } from 'vue'
const store = useCounterStore()
-// ❌ 这将不起作用,因为它破坏了响应性
-// 这就和直接解构 `props` 一样
+// ❌ 下面这部分代码不会生效,因为它的响应式被破坏了
+// 它和解构 `props` 的操作是一样的
const { name, doubleCount } = store // [!code warning]
-name // 将始终是 "Eduardo" // [!code warning]
-doubleCount // 将始终是 0 // [!code warning]
+name // 将会一直是 "Eduardo" // [!code warning]
+doubleCount // 将会一直是 0 // [!code warning]
setTimeout(() => {
store.increment()
}, 1000)
-// â\9c\85 è¿\99æ ·å\86\99æ\98¯å\93\8dåº\94å¼\8fç\9a\84
-// ð\9f\92¡ å½\93ç\84¶你也可以直接使用 `store.doubleCount`
+// â\9c\85 è\80\8cè¿\99ä¸\80é\83¨å\88\86代ç \81å°±ä¼\9aç»´æ\8c\81å\93\8dåº\94å¼\8f
+// ð\9f\92¡ å\9c¨è¿\99é\87\8c你也可以直接使用 `store.doubleCount`
const doubleValue = computed(() => store.doubleCount)
</script>
```
<script setup>
import { storeToRefs } from 'pinia'
const store = useCounterStore()
-// `name` 和 `doubleCount` 是响应式的 ref
-// 同时通过插件添加的属性也会被提取为 ref
-// 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
+// `name` 和 `doubleCount` 都是响应式引用
+// 下面的代码同样会提取那些来自插件的属性的响应式引用
+// 但是会跳过所有的 action 或者非响应式(非 ref 或者 非 reactive)的属性
const { name, doubleCount } = storeToRefs(store)
-// 作为 action 的 increment 可以直接解构
+// 名为 increment 的 action 可以被解构
const { increment } = store
</script>
```