vue3中的pinia使用

1.安装

npm install pinia

2.挂载到main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createPinia } from 'pinia'

// 创建pinia 实例
const pinia = createPinia()
createApp(App).use(router).use(pinia).mount('#app')

3.在页面中引入








3.在store下创建index.js

import { defineStore } from 'pinia'
import { userStore } from './user.js'

export const mainStore = defineStore('main', {
    state: () => {
        return {
            helloWorld: "helloWorld",
            count: 0,
            phone: '13120907614',
            listArray: userStore().list
        }
    },
    getters: {
        phoneHidden(state) {
            return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
        },

    },
    actions: {
        // 在用actions的时候,不能使用箭头函数,因为箭头函数绑定是外部的this
        changeState() {
            this.count++
            this.helloWorld = '通过action改变'
        },
        getList(){
            console.log(userStore().list)
        }
    }
})

4.user.js

import { defineStore } from 'pinia'
export const userStore = defineStore('user', {
    state: () => {
        return {
            list: ['小红', '小美', '小红']
        }
    },
    getters: {
        phoneHidden(state) {
            return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
        }

    },
    actions: {
        
    }
})

你可能感兴趣的:(vue3中的pinia使用)