pinia(vue3推荐)
- 首先下载pinia
npm i pinia // "pinia": "^2.0.14"
- 创建pinpa.js
//解构pinia中的createPinia用于创建pinia实例
import { createPinia } from "pinia";
//实例化pinia
const store = createPinia();
export function piniaStore(app) {
//注册给app
app.use(pinia)
}
- 引入到main.js
// 引入pinia
import {piniaStore} from "@/plugin/pinia.js"
piniaStore(app)
- 在stores里的js文件里定义数据
import { defineStore } from "pinia";
export const userInfo = defineStore("userinfo", {
id:"userInfo",
//定义要管理的数据
state: () => {
return {
userid: "1001111",
username: "张三",
age: 20,
address: "北京",
};
},
//要处理的业务逻辑方法
actions: {
fn(val){
this.username=val
}
},
//通过state处理的计算属性
getters: {}
});
- 定义store,及修改store的数据
<template>
<div class="index_page">
{{store.username}}//在页面上可以呈现
</div>
<button @click="click">点击改名</button>
</template>
<script setup>
import {userInfo} from '@/stores/userInfo.js'
const store=userInfo()
const click=()=>{
store.fn('李大漂亮')
}
</script>
pinia-plugin-persistedstate
- 下载pinia-plugin-persistedstate数据持久化
pnpm : pnpm i pinia-plugin-persistedstate
npm : npm i pinia-plugin-persistedstate
yarn : yarn add pinia-plugin-persistedstate
- 在piniajs文件中引入
//解构pinia中的createPinia用于创建pinia实例
import { createPinia } from "pinia";
//实例化pinia
const store = createPinia();
//引入持久化插件
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
//pinia使用
pinia.use(piniaPluginPersistedstate)
export function piniaStore(app) {
//注册给app
app.use(pinia)
- 在stores文件里加上persist:true
import { defineStore } from "pinia"
export const useCounterStore = defineStore({
persist: true,//!!!!!!!!!!!!!!!!!!!!!!!!!!!!
id: "counter",
state: () => ({
home_title: "",
}),
getters: {},
actions: {
getHomeTitle(val) {
this.home_title = val
},
},
})
在本地存储的话会有一个默认的存储名称,那么我们改如何修改呢如何
改变本地存储的名称和改变存储的位置
//数据持久化
import { defineStore } from "pinia"
export const useCounterStore = defineStore({
///
persist: {
key: "给一个要保存的名称",
//保存的位置
storage: window.sessionStorage,//localstorage
},
///
id: "counter",
state: () => ({
home_title: "",
}),
getters: {},
actions: {
getHomeTitle(val) {
this.home_title = val
},
},
})
这样刷新数据就不会丢失了