---
# System prepended metadata

title: pinia ( with Vue cli )

---

# pinia ( with Vue cli )

## 安裝環境
`npm install pinia`

## 配置檔案
### main.js
```
import { createPinia } from 'pinia'

const pinia = createPinia()

app.use(pinia)
```

### stores/[name].js
```
import { defineStore } from 'pinia'

// 第一個變數可自由命名
export default defineStore('User Store', {
  // data
  state: () => ({
    name: 'w11',
    money: 300
  }),

  // Computerd
  getters: {
    getUserName () {
      return `我的名字叫做 ${this.name}`
    }
  },

  // Methods
  actions: {
    updateName () {
      this.name = 'w22'
    }
  }
})

```

## 使用 store
```
import userStore from '@/stores/[name]'
import { storeToRefs } from 'pinia'

export default {
  setup () {
    // reactive
    const user = userStore()
    // ref
    const { name, money, getUserName } = storeToRefs(user)
    // action
    const { updateName } = user
    // patch
    const updateData = function () {
      user.$patch({
        name: 'w33',
        money: 500
      })
    }
    // reset
    const reset = function () {
      user.$reset()
    }

    return {
      user,
      name,
      money,
      getUserName,
      updateName,
      updateData,
      reset
    }
  }
}
```