记录pinia在vue2中的使用

8,254 阅读1分钟

1.安装

import Vue from 'vue'
import App from './App.vue'
import { createPinia, PiniaVuePlugin } from 'pinia'
import { createPersistedState } from 'pinia-persistedstate-plugin'
Vue.use(PiniaVuePlugin)
const pinia = createPinia()
pinia.use(createPersistedState()) //开启缓存,存储在localstorage

Vue.use(Antd)
new Vue({
  pinia,
  render: h => h(App),
}).$mount('#app')

2.定义store

import { defineStore } from 'pinia'
const useStore = defineStore('store', {
    // 开启数据缓存
    persist: {
        enabled: true
    },
    state: () => {
        return {
            tagslist: [{
                title: '首页',
                key: 'home',
                closable: false
            }],
        }
    },
    actions: {
        changeTagList(obj) {
            const key = this.tagslist.find(item => {
                return item.key == obj.key
            })
            if (!key) {
                this.tagslist.push(obj)
            }
        },
        deleteTagList(k) {
            const key = this.tagslist.findIndex(item => {
                return item.key == k
            })
            this.tagslist.splice(key, 1)
        },
    }
})
export default useStore

pinia不需要mutation,只需要使用action来改变状态

3.使用

.vue文件
<script>
import { mapState,mapActions } from 'pinia' //引入映射函数
import useStore from '../../../store/index' //引入store
export default {
    data() {
        return {

        };
    },
    computed:{
        ...mapState(useStore,["tagslist"]) //映射函数,取出tagslist
    },
    methods: {
        ...mapActions(useStore, ['changeTagList']), //映射action
        toUrl(item) {
            const obj = {
                title: item.meta.title,
                key: item.name,
            }
            this.changeTagList(obj) //直接使用action改变状态
            this.$router.push({
                name:item.name
            }).catch(() => {})
        },
    },
};
</script>