用pinia缓存数据
时间: 2023-11-20 14:57:39 浏览: 24
使用Pinia缓存数据的步骤如下:
1.首先,安装Pinia库。可以使用以下命令进行安装:
```shell
npm install pinia
```
2.在Vue应用程序中创建一个store.js文件,并在其中导入Pinia和Vue:
```javascript
import { createPinia } from 'pinia'
import { App } from 'vue'
const pinia = createPinia()
export function setupStore(app: App<Element>) {
app.use(pinia)
}
```
3.在Vue组件中使用Pinia:
```javascript
import { defineComponent } from 'vue'
import { useUserStore } from '@/store/user'
export default defineComponent({
setup() {
const userStore = useUserStore()
// 从缓存中获取用户信息
const userInfo = userStore.getUserInfoFromCache()
return {
userInfo, }
},
})
```
4.在store.js文件中定义一个store,用于缓存数据:
```javascript
import { defineStore } from 'pinia'
export const useUserStore = defineStore({
id: 'user',
state: () => ({
userInfo: null,
}),
actions: {
// 将用户信息存储到缓存中
setUserInfo(userInfo) {
localStorage.setItem('userInfo', JSON.stringify(userInfo))
this.userInfo = userInfo
},
// 从缓存中获取用户信息
getUserInfoFromCache() {
const userInfo = JSON.parse(localStorage.getItem('userInfo'))
this.userInfo = userInfo
return userInfo
},
},
})
```
5.在Vue组件中使用store:
```javascript
import { defineComponent } from 'vue'
import { useUserStore } from '@/store/user'
export default defineComponent({
setup() {
const userStore = useUserStore()
// 将用户信息存储到缓存中
userStore.setUserInfo(userInfo)
return {
userInfo,
}
},
})
```