使用vue-cli创建项目
vue create vue2pinia
cd vue2pinia
npm install
npm run serve // 初始化项目运行OK
安装pinia模块
npm i pinia pinia-plugin-persistedstate
引入pinia模块
- 创建store/index.js
// index.js
import Vue from 'vue'
import { createPinia, PiniaVuePlugin } from 'pinia'
import pps from 'pinia-plugin-persistedstate'
Vue.use(PiniaVuePlugin)
const pinia = createPinia()
pinia.use(pps)
export default pinia
// 多模块中转
export * from './modules/userInfo'
// userInfo.js
import { defineStore } from 'pinia'
export const useUserStore = defineStore('userInfo', {
state: ()=> {
return {
name: 'java',
token: '',
count: 100
}
},
actions: {
setToken(val) {
this.token = val
},
setName(val) {
this.name = val
},
setCount(val) {
this.count += val
}
},
getters: {
double: (state)=> {
return state.count * 2
}
},
persist: true // 开启当前模块的持久化
})
在main.js中引入pinia
import pinia from '@/store'
new Vue({
render: h => h(App),
pinia
}).$mount('#app')
在组件中使用仓库数据
import { useUserStore } from '@/store'
import { mapState, mapActions } from 'pinia' // 类似vuex
export default {
name: 'App',
computed: {
...mapState(useUserStore, ['count']) // mapState(store对象, ['属性名称'])
},
created() {
const user = useUserStore()
console.log(user.count)
},
methods: {
...mapActions(useUserStore, ['setToken', 'setCount']) // mapActions(store对象, ['方法名称'])
}
}
![](https://img.haomeiwen.com/i3086615/1a342a788a53f63f.png)
页面展示.png
![](https://img.haomeiwen.com/i3086615/e81456cf75b24adb.png)
pinia仓库展示.png
网友评论