vue,我登陆之后,怎么让登录接口的id进行全局缓存,在其他的页面也能调用到这个id
时间: 2024-03-19 13:45:14 浏览: 21
您可以将该 ID 存储在 Vuex 状态管理中,以便在全局范围内访问它。具体步骤如下:
1. 在你的 Vue 项目中安装 Vuex 。你可以使用 npm 或者 yarn 安装它:
```
npm install vuex --save
```
或者
```
yarn add vuex
```
2. 在你的 src 目录中创建一个名为 store.js 的文件。
3. 在 store.js 文件中导入 Vuex 并创建一个 Vuex store。
```
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
userId: null
},
mutations: {
setUserId(state, id) {
state.userId = id
}
},
actions: {
setUserId({ commit }, id) {
commit('setUserId', id)
}
}
})
export default store
```
4. 在你的 main.js 文件中导入 store.js 文件,并使用它。
```
import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
store,
render: h => h(App)
}).$mount('#app')
```
5. 在你的登录页面中调用 actions 中的 setUserId 函数来设置 ID 的值。
```
methods: {
login() {
// 调用接口,获取 ID 的值
const id = 'your id'
// 调用 Vuex 的 action 来设置 ID 的值
this.$store.dispatch('setUserId', id)
}
}
```
6. 在其他页面中,你可以使用 state 中的 userId 属性来访问该 ID 的值。
```
computed: {
userId() {
return this.$store.state.userId
}
}
```
或者你可以使用 mapState 辅助函数来访问该 ID 的值。
```
import { mapState } from 'vuex'
computed: {
...mapState(['userId'])
}
```
这样,在你的应用程序的任何地方,你都可以使用 this.$store.state.userId 或者 this.userId 来访问您的 ID 的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)