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())
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'
export default {
data() {
return {
};
},
computed:{
...mapState(useStore,["tagslist"])
},
methods: {
...mapActions(useStore, ['changeTagList']),
toUrl(item) {
const obj = {
title: item.meta.title,
key: item.name,
}
this.changeTagList(obj)
this.$router.push({
name:item.name
}).catch(() => {})
},
},
};
</script>