vue3+js+vite+pinia

1.使用vite创建项目

npm init vite@latest

vue3+js+vite+pinia_第1张图片

2.安装vite和vite的持久化插件

//安装pinia
npm install pinia

//安装持久化插件
npm install pinia-plugin-persist --save

3.新建store/index.js

import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'

const store = createPinia()
store.use(piniaPluginPersist)

export default store

4.在main.js中进行挂载

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import store from './store'

createApp(App).use(store).mount('#app')

5.创建store/main.js

import { defineStore } from "pinia";

export  const useMainStore = defineStore('main',{
    state: ()=>({
       count: 45,
       name : "张三"
    }),
    getters:{
        doubleCount(state){
            return state.count * 2
        },
        doubleCountPlus(){
            return this.doubleCount + 1
        },
        customDoubleCount(){
            return (a)=>{
                return this.doubleCount + a;
            }
        }
    },
    actions:{
        addOneMult(num){
            this.count += num;
        }
    },
    persist: {
        enabled: true,
        strategies: [
            {   key:'fast-admin-main',
                storage: localStorage,
                //限制存储内容,不配置的话存储所有
                paths: ['count', 'name']
            }
        ]
    }

})

6.测试App.vue




你可能感兴趣的:(vue,vue3,pinia)