pinia-状态管理使用(pinia持久化、pinia状态管理、vue状态管理、vue3状态)

安装及引用

// 安装 pinia
npm install pinia -S

// 在main.js挂载
import {createPinia} from 'pinia'
const pinia = createPinia()
createApp(App).use(pinia).mount("#app");


创建store

  1. 在src下创建piniaStore/storeA.js
import { defineStore } from "pinia";

export const storeA = defineStore("storeA", {
  state: () => {
    return {
      piniaMsg: "hello pinia",
      piniaName: '小七',
      piniaAge: 25
    };
  },
  getters: {},
  actions: {
    // edit_name(){

    // }
  },
});
  1. 在app.vue中使用
<template>
  <div class="Box">
    <div class="title">
      首页
    </div>
    {{piniaStore_storeA.piniaMsg}}
  </div>
</template>

<script>
import { storeA } from '../../piniaStore/storeA'
export default {
  name: 'homeIndexPage',
  setup () {
    let piniaStore_storeA = storeA()
    return {
      piniaStore_storeA
    }
  }
}
</script>
  1. 将数据store挂载到公共方法上(第二种用法)

a. 挂载

import { createApp } from 'vue'
import App from './App.vue'
import store from './store/index'
import router from './/router/index'
import { createPinia } from 'pinia'
import { storeA } from './piniaStore/storeA'
const pinia = createPinia()

// 创建appvue
const app = createApp(App)
app.use(pinia)
app.config.globalProperties.$Fn = storeA()
app.use(store)
app.use(router)
app.mount('#app')

b. 在app.vue中使用

<template>
  <div>
    {{proxy.$piniaStor_storeA.piniaMsg}}
  </div>
</template>

<script>
import { getCurrentInstance } from '@vue/runtime-core'
import { storeA } from '../../piniaStore/storeA'
export default {
  name: 'homeIndexPage',
  setup () {
    let piniaStore_storeA = storeA()
    const { proxy } = getCurrentInstance()
    return {
      piniaStore_storeA,
      proxy
    }
  }
}
</script>

修改状态

直接修改

<template>
  <div class="Box">
    年龄:{{proxy.$piniaStor_storeA.piniaAge}}

  </div>
  <el-button @click="fn_reduce"
             class="buttonCss">减少</el-button>
  <el-button @click="fn_add"
             style="margin:20px"
             class="buttonCss">增多</el-button>
</template>

<script>
import { getCurrentInstance } from '@vue/runtime-core'
import { storeA } from '../../piniaStore/storeA'
export default {
  name: 'homeIndexPage',
  setup () {
    let piniaStore_storeA = storeA()
    const { proxy } = getCurrentInstance()

    let fn_add = () => {
      piniaStore_storeA.piniaAge++
    }
    let fn_reduce = () => {
      proxy.$piniaStor_storeA.piniaAge--
    }
    return {
      piniaStore_storeA,
      proxy,
      fn_add,
      fn_reduce
    }
  }
}
</script>

$patch修改

简介:$patch:可以进行多个状态修改也可以单个状态修改

  1. 普通修改
piniaStore_storeA.$patch({
        piniaAge: 15,
        piniaName: 'danguner'
})
  1. 函数方式修改
 piniaStore_storeA.$patch((state) => {
        state.piniaAge = 25
        state.piniaName = '小七'
})

在actions中进行修改

注册action方法

import { defineStore } from "pinia";

export const storeA = defineStore("storeA", {
  state: () => {
    return {
      piniaMsg: "hello pinia",
      piniaName: '小七',
      piniaAge: 25
    };
  },
  getters: {},
  actions: {
    edit_name (data) {
      this.piniaName = data
    },
  },
});

在app.vue中使用

<template>
  <div class="Box">
    年龄:{{proxy.$piniaStor_storeA.piniaAge}}
    姓名:{{proxy.$piniaStor_storeA.piniaName}}

  </div>
  <el-button @click="fn_changeName('danguner')"
    class="buttonCss">danguner</el-button>
  <el-button @click="fn_changeName('小七')"
    style="margin:20px"
    class="buttonCss">小七</el-button>
</template>

<script>
  import { getCurrentInstance } from '@vue/runtime-core'
  import { storeA } from '../../piniaStore/storeA'
  export default {
    name: 'homeIndexPage',
    setup () {
      let piniaStore_storeA = storeA()
      const { proxy } = getCurrentInstance()

      let fn_changeName = (data) => {
        console.log(data, 'data')
        piniaStore_storeA.edit_name(data)
      }

      return {
        piniaStore_storeA,
        proxy,
        fn_changeName
      }
    }
  }
</script>

重置state–$reset()

Pinia可以使用$reset将状态重置为初始值

import { storeA } from '@/piniaStore/storeA' 
let piniaStoreA = storeA()
piniaStoreA.$reset()

getters

注册

import { defineStore } from "pinia";

export const storeA = defineStore("storeA", {
  state: () => {
    return {
      piniaMsg: "hello pinia",
      piniaName: '小七',
      
      piniaAge: 25
    };
  },
  getters: {
    Introduction_data () {
      return `姓名:${this.piniaName}--->年龄${this.piniaAge}`
    }
  },
  actions: {
    edit_name (data) {
      this.piniaAge = data == 'danguner' ? 18 : 25
      this.piniaName = data
    },
  },
});

在app.vue页面使用

<template>
  <div class="Box">
    {{proxy.$piniaStor_storeA.Introduction_data}}

  </div>
  <el-button @click="fn_changeName('danguner')"
             class="buttonCss">danguner</el-button>
  <el-button @click="fn_changeName('小七')"
             style="margin:20px"
             class="buttonCss">小七</el-button>
</template>

<script>
import { getCurrentInstance } from '@vue/runtime-core'
import { storeA } from '../../piniaStore/storeA'
export default {
  name: 'homeIndexPage',
  setup () {
    let piniaStore_storeA = storeA()
    const { proxy } = getCurrentInstance()

    let fn_changeName = (data) => {
      console.log(data, 'data')
      piniaStore_storeA.edit_name(data)
    }

    return {
      piniaStore_storeA,
      proxy,
      fn_changeName
    }
  }
}
</script>

<style lang="less" scoped>
@color: #0982c1;
.text3d(@color) {
  color: @color;
  text-shadow: 1px 1px 0px darken(@color, 5%), 2px 2px 0px darken(@color, 10%),
    3px 3px 0px darken(@color, 15%), 4px 4px 0px darken(@color, 20%),
    4px 4px 2px #000;
}
@keyframes xz {
  from {
    transform: rotateY(0);
  }
  to {
    transform: rotateY(360deg);
  }
}
.Box {
  background: aqua;
  width: 100%;
  height: 80vh;
  text-align: center;
  line-height: 80vh;
  font-size: 50px;
  .title {
    animation: xz 5s linear infinite;
  }
  .text3d(#0982c1);
}
.buttonCss {
  cursor: pointer;
  padding: 0.3125rem;
  border: 0.0625rem solid blue;
  box-sizing: border-box;
  &:hover {
    color: aquamarine;
  }
}
</style>

数据持久化

pinia-plugin-persistedstate 数据持久化

  1. 安装
npm i pinia-plugin-persistedstate
  1. 引入注册
import { createApp } from 'vue'
import './style.css'
import router from '@router/index.js'
import App from './App.vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
createApp(App)
  .use(router)/**挂载路由 */
  .use((createPinia().use(piniaPluginPersistedstate)))/**挂载状态管理 pinia */
  .mount('#app')

  1. 将state数据保存在localstorage(关闭浏览器数据清空)

import { defineStore } from "pinia";
export const storeA = defineStore("storeA_pinia", {
  state: () => {
    return {
      piniaMsg: "hello pinia",
      piniaName: '小七',
      piniaAge: 25
    };
  },
  getters: {},
  actions: {
  },
  // 持久化插件使用
  // persist:true
  persist: {
    storage: localStorage,//sessionStorage
    paths: ['piniaName']
  }
});


pinia-plugin-persist 数据持久化

  1. 安装
npm i pinia-plugin-persist
  1. 注册挂载
import { createApp } from 'vue'
import './style.css'
import router from '@router/index.js'
import App from './App.vue'
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
const pinia = ((createPinia()).use(piniaPluginPersist))
createApp(App)
  .use(router)/**挂载路由 */
  .use(pinia)/**挂载状态管理 pinia */
  .mount('#app')

  1. 使用
import { defineStore } from "pinia";
export const storeA = defineStore("storeA_pinia", {
  state: () => {
    return {
      piniaMsg: "hello pinia",
      piniaName: '小七',
      piniaAge: 25
    };
  },
  getters: {},
  actions: {
  },
  // 持久化插件使用
  // persist:true
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'storeA_pinia',
        storage: sessionStorage, // localStorage
        paths: ['piniaName']
      },
    ],
  },
});

项目示例

import { createApp } from 'vue'
import './style.css'
import router from '@router/index.js'
import App from './App.vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = ((createPinia()).use(piniaPluginPersistedstate))
createApp(App)
  .use(router)/**挂载路由 */
  .use(pinia)/**挂载状态管理 pinia */
  .mount('#app')

import { storeA } from './moudule/storeA.js'
import { getters } from './getters'
export default {
  getters: getters,
  storeA: storeA
}
import { defineStore } from "pinia";
import { storeA } from './moudule/storeA'
export const getters = defineStore("getters", {
  state: () => {
    return {
    };
  },
  getters: {
    piniaName() {
      return storeA().piniaName
    }
  },
});
import { defineStore } from "pinia";
export const storeA = defineStore("storeA_pinia", {
  state: () => {
    return {
      piniaMsg: "hello pinia",
      piniaName: '小七',
      piniaAge: 25
    };
  },
  getters: {},
  actions: {
  },
  // 持久化插件使用
  // persist:true
  persist: {
    storage: localStorage,//sessionStorage
    paths: ['piniaName']
  }
});
<template>
    <span @click="routeLogin">首页</span>
    {{ store.getters().piniaName }}
    <div @click="changeName">修改name</div>
    <div @click="restName">重置name</div>
</template>
<script setup>
import {useRoute,useRouter} from 'vue-router'
// import { storeA } from '@store/moudule/storeA.js'
import store from '@store/index.js'
const route = useRoute()
const router = useRouter()
const store_sl = store.storeA()
console.log(useRoute(),'useRoute')
/**
 * router.push()
   router.back()
   router.replace()
 */
const routeLogin = ()=>{
    router.push('./Login')
}
const changeName = ()=>{
  store_sl.piniaName+='1'
}
const restName = ()=>{
  store_sl.$reset()
}
  
</script>
<style scoped>
span{
  cursor: pointer;
}
</style>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值