vue3.0 + ts 使用 pinia

153 阅读1分钟

1、安装 pinia

yarn add pinia
# 或者使用 npm
npm install pinia

2、引入在main.ts中使用

// store/index.ts

import type { App } from 'vue'
import { createPinia } from 'pinia'

const store = createPinia()

export { store }

// main.ts

import { createApp, h } from 'vue'
import App from './App.vue'

const setupAll = async () => {
  const app = createApp({
    beforeCreate: () => {
      console.log('beforeCreate')
    },
    render: () => h(App)
  })
  app.use(store)
  app.mount('#app')
}

setupAll()

3、pinia模块写法 // types/store.d.ts

export type KeysType = {
   a: string,
   b: string,
   c: string
}

// store/modules/app.ts

import { defineStore } from 'pinia'
import type { KeysType } from '@/types/app.d'
import { defineStore } from 'pinia'
import { store } from '../index'

interface AppState {
  params: KeysType
}


export const useAppStore = defineStore('app', {
  state: (): AppState => ({
    params: {
      a: '',
      b: '',
      c: ''
    }
  }),
  actions: {
    setParams(params: KeysType) {
      this.params = params
    }
  }
})

export const useAppStoreWithOut = () => {
  return useAppStore(store)
}

4、引入使用 // 首次使用文件

import { useAppStoreWithOut } from '@/store/modules/app'
const appStore = useAppStoreWithOut()

// 导出值
const params = appStore.params

// 使用方法
appStore.setParams({
    a: '1',
    b: '2',
    c: '3'
})

// 其他地方使用

import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()

// 导出值
const params = appStore.params

// 使用方法
appStore.setParams({
    a: '1',
    b: '2',
    c: '3'
})