### 1. 创建空Vue项目
```bash
npm init vue@latest
```

### 2. 安装Pinia并注册
```bash
npm i pinia
```

```javascript

import { createPinia } from 'pinia'

const app = createApp(App)
// 以插件的形式注册
app.use(createPinia())
app.use(router)
app.mount('#app')
```
# 实现counter
> 核心步骤:
> 1. 定义store
> 2. 组件使用store

1- 定义store
```javascript
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCounterStore = defineStore('counter', ()=>{
  // 数据 (state)
  const count = ref(0)

  // 修改数据的方法 (action)
  const increment = ()=>{
    count.value++
  }

  // 以对象形式返回
  return {
    count,
    increment
  }
})

```
2- 组件使用store
```vue
<script setup>
  // 1. 导入use方法
	import { useCounterStore } from '@/stores/counter'
  // 2. 执行方法得到store store里有数据和方法
  const counterStore = useCounterStore()
</script>

<template>
	<button @click="counterStore.increment">
    {{ counterStore.count }}
  </button>
</template>
```

By lxcss

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注