美文网首页
vue2.x优雅的使用pinia

vue2.x优雅的使用pinia

作者: 桥下醉翁 | 来源:发表于2024-02-25 16:39 被阅读0次

使用vue-cli创建项目

vue create vue2pinia
cd vue2pinia
npm install
npm run serve // 初始化项目运行OK

安装pinia模块

npm i pinia pinia-plugin-persistedstate

引入pinia模块

  1. 创建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对象, ['方法名称'])
  }
}
页面展示.png pinia仓库展示.png

相关文章

网友评论

      本文标题:vue2.x优雅的使用pinia

      本文链接:https://www.haomeiwen.com/subject/ipmoqdtx.html