---
一、 LocalStorage
**LocalStorage** 是 Web 存储的一种,用来在用户的浏览器中存储数据。以下是 LocalStorage 的一些关键点:
- **数据存储**:
- LocalStorage 允许存储键值对(key-value pairs)。
- 数据存放在浏览器中,不同域之间无法共享。
- 存储的数据是持久化的,即使在浏览器关闭后,数据仍然存在。
- **存储容量**:
- 通常每个域大约可以存储 5MB 的数据(浏览器的具体实现可能会有所不同)。
- **常用 API**:
- `localStorage.setItem(key, value)`:存储数据。
- `localStorage.getItem(key)`:获取存储的数据。
- `localStorage.removeItem(key)`:删除指定键的数据。
- `localStorage.clear()`:清空所有的 LocalStorage 数据。
- **实例**:
```javascript
// 存储数据
localStorage.setItem('username', 'JohnDoe');
// 获取数据
const username = localStorage.getItem('username');
console.log(username); // 输出: JohnDoe
// 删除数据
localStorage.removeItem('username');
// 清空所有数据
localStorage.clear();
```
二、Vuex
**Vuex** 是一个状态管理模式 + 库,用于 Vue.js 应用程序,专门用于管理组件之间的状态共享。以下是有关 Vuex 的核心概念:
- **核心概念**:
- **State**:存储应用程序的所有状态,采用一个对象来保存。
- **Getters**:从状态中派生出状态,类似于 Vue 计算属性,允许在状态变化时重新计算。
- **Mutations**:用于修改状态的方法,必须是同步的。
- **Actions**:用于处理异步操作的,可以包含任何异步操作(例如 API 调用),最后提交 Mutations。
- **Modules**:允许将 store 分割成模块,每个模块拥有自己的 state、mutations、actions 和 getters。
- **基本使用**:
```javascript
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
asyncIncrement({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
}
},
getters: {
doubleCount(state) {
return state.count * 2;
}
}
});
export default store;
```
- **在组件中使用**:
```javascript
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
<button @click="asyncIncrement">Async Increment</button>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
computed: {
...mapState(['count']),
},
methods: {
...mapActions(['increment', 'asyncIncrement']),
}
}
</script>
```
三、路由前置守卫
**路由前置守卫** 是 Vue Router 中的功能,用于在路由切换前进行判断或处理,常用于权限控制、数据预加载等。-
**定义和使用**:
- 在 Vue Router 中,可以通过 `beforeEach` 方法定义全局前置守卫。
- 也可以在单个路由配置中使用 `beforeEnter` 定义局部前置守卫。
- **全局前置守卫**:
```javascript
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
const router = new Router({
routes: [
// 定义路由
]
});
router.beforeEach((to, from, next) => {
// 这里可以进行认证、检查权限等
const isAuthenticated = false; // 替换为实际的身份验证逻辑
if (to.meta.requiresAuth && !isAuthenticated) {
next({ name: 'Login' }); // 重定向到登录页
} else {
next(); // 确定放行
}
});
export default router;
```
- **局部前置守卫**:
```javascript
const router = new Router({
routes: [
{
path: '/protected',
component: ProtectedComponent,
beforeEnter: (to, from, next) => {
const isAuthenticated = false; // 替换为实际的身份验证逻辑
if (isAuthenticated) {
next();
} else {
next({ name: 'Login' });
}
}
}
]
});
```
四、 总结
- **LocalStorage** 用于在浏览器中存储数据,数据持久化,不同页面共享。
- **Vuex** 用于管理 Vue 应用的状态,提供了集中式存储。
- **路由前置守卫** 允许在路由切换前进行一些检查或操作,确保用户的访问权限和数据状态。