vue3--Pinia状态管理


安装

npm install pinia --save

使用

创建store文件夹

建 src/store 目录并在其下面创建 index.ts,导出 store

// src/store/index.ts
import { createPinia } from 'pinia'

const store = createPinia()

export default store

在 main.ts 中引入并使用

// src/main.ts

import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

const app = createApp(App)
app.use(store)

创建login.ts文件

建 src/store 目录并在其下面创建 module/login.ts文件,用来单独管理各个模块

// src/store/module/login.ts
import { ref } from 'vue'
import { defineStore } from 'pinia'

export const useLoginStoreSetup = defineStore('useLoginStoreSetup', {
  // Composition API写法
  // const count = ref(0)
  // const getCount = () => {
  //   return count.value * 2
  // }
  // const incurment = () => {
  //   count.value++
  // }

  // return {
  //   count,
  //   getCount,
  //   incurment
  // }

  // options API写法
  state: () => ({
    count: 0,
	sum: 0
  }),
  getters: {
    dobule: (state) => state.count
  },
  actions: {
    incurment() {
      this.count++
	  this.sum++
    },
  }
})

获取store




vue