第一步安装pinia
npm install pinia
安装pinia插件
npm install pinia-plugin-persist
新建store文件夹建立index.ts文件
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
const store = createPinia()
store.use(piniaPluginPersist)
export default store
建立 userStore.ts文件
import { defineStore } from 'pinia'
export const userStore = defineStore({
id: 'user',
state:()=>{
return {
name:""
}
},
getters:{
},
actions:{
},
// 开启数据缓存
persist: {
enabled: true,
strategies: [
{
key: 'my_user',
storage: localStorage,
}
]
}
})
在main.ts里面导入store
//导入store
import store from './store'
这时的main.ts整体
import { createApp } from 'vue'
import App from './App.vue'
//加入路由
import router from './router/index';
//并通过use,使用路由
//导入store
import store from './store'
const app=createApp(App)
app.use(router)
//使用store
app.use(store)
app.mount('#app')
在登录页面
<template>
登录页面
<input type="text" v-model="inputname" />
<button @click="btn">按钮</button>
</template>
<script lang="ts" setup>
import { userStore } from "../store/userStore";
import { storeToRefs } from "pinia";
import { ref } from "vue";
const inputname = ref("aa");
let { name } = storeToRefs(userStore());
const btn = () => {
console.log(inputname.value)
name.value = inputname.value;
};
</script>