vue3 使用 pinia 组件

vue yekong 369℃

随着项目框架想着vue3转移,一些依赖的插件也发生了变化,以前使用的是vuex,最近改为了pinia组件,一些写法不清楚咋写的,需要梳理一下。习惯了vue2的写法,虽然框架改为了vue3很多写法还是沿用的vue2.

安装依赖

pnpm i pinia

创建store.js

import {
    defineStore
} from 'pinia'

// 创建store,命名规则: useXxxxStore
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters

export const useCounterStore = defineStore('counter', {
    // data里中的数据
    state: () => ({
        itemIndex: 0
    }),
    // 计算属性
    getters: {
        double: state => state.itemIndex * 2
    },
    // 相当于 vue中的 methods 既可以写同步代码也可以写异步
    actions: {
        changeItemIndex(itemIndex) {
            this.itemIndex = itemIndex
        }
    }
})

获取值

import {mapState, mapActions} from 'pinia'
import {useCounterStore} from '@/store/index'

computed: {
    ...mapState(useCounterStore, ['itemIndex'])
},

更新值

import {mapState, mapActions} from 'pinia'
import {useCounterStore} from '@/store/index'
const store = useCounterStore()

store.changeItemIndex(e.dataIndex)
喜欢 (0)