VUEX项目场景
一、登录状态存储
<template>
<div>
<input v-model="username" type="text" placeholder="Username">
<input v-model="password" type="password" placeholder="Password">
<button @click="login">Login</button>
<div v-if="error" style="color: red;">{{ error }}</div>
</div>
</template>
<script>
import { mapActions } from 'vuex';
export default {
data() {
return {
username: '',
password: '',
error: ''
};
},
methods: {
...mapActions(['login']),
async login() {
try {
await this.$store.dispatch('login', {
username: this.username,
password: this.password
});
this.$router.push('/');
} catch (error) {
this.error = 'Login failed. Please check your username and password.';
}
}
}
};
</script>
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const LOGIN_STATUS_KEY = 'loginStatus';
const USER_KEY = 'user';
const store = new Vuex.Store({
state: {
isLoggedIn: localStorage.getItem(LOGIN_STATUS_KEY) === 'true',
user: JSON.parse(localStorage.getItem(USER_KEY))
},
mutations: {
SET_LOGIN_STATUS(state, status) {
state.isLoggedIn = status;
localStorage.setItem(LOGIN_STATUS_KEY, status);
},
SET_USER(state, user) {
state.user = user;
localStorage.setItem(USER_KEY, JSON.stringify(user));
}
},
actions: {
login({ commit }, userData) {
const user = { username: userData.username };
commit('SET_USER', user);
commit('SET_LOGIN_STATUS', true);
},
logout({ commit }) {
commit('SET_USER', null);
commit('SET_LOGIN_STATUS', false);
}
},
getters: {
isLoggedIn: state => state.isLoggedIn,
currentUser: state => state.user
}
});
export default store;
二、购物车案例
// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
// 创建 Vuex store 实例
const store = new Vuex.Store({
// 定义状态
state: {
// 购物车中的商品列表
cart: []
},
// 定义同步修改状态的方法
mutations: {
// 添加商品到购物车
ADD_TO_CART(state, product) {
// 检查购物车中是否已存在相同商品
const item = state.cart.find(item => item.id === product.id);
if (item) {
// 如果存在相同商品,增加商品数量
item.quantity++;
} else {
// 如果不存在相同商品,将商品添加到购物车列表中
state.cart.push({ ...product, quantity: 1 });
}
},
// 从购物车中移除商品
REMOVE_FROM_CART(state, productId) {
// 过滤掉要移除的商品
state.cart = state.cart.filter(item => item.id !== productId);
},
// 更新购物车中商品的数量
UPDATE_QUANTITY(state, payload) {
// 从 payload 中获取商品 ID 和新的数量
const { productId, quantity } = payload;
// 查找对应商品
const item = state.cart.find(item => item.id === productId);
if (item) {
// 更新商品数量
item.quantity = quantity;
}
},
// 清空购物车
CLEAR_CART(state) {
// 将购物车列表置为空数组
state.cart = [];
}
},
// 定义异步操作或者包含逻辑的方法
actions: {
// 添加商品到购物车的 action
addToCart({ commit }, product) {
// 提交 ADD_TO_CART mutation,传递商品信息
commit('ADD_TO_CART', product);
},
// 从购物车中移除商品的 action
removeFromCart({ commit }, productId) {
// 提交 REMOVE_FROM_CART mutation,传递商品 ID
commit('REMOVE_FROM_CART', productId);
},
// 更新购物车中商品数量的 action
updateQuantity({ commit }, payload) {
// 提交 UPDATE_QUANTITY mutation,传递商品 ID 和新的数量
commit('UPDATE_QUANTITY', payload);
},
// 清空购物车的 action
clearCart({ commit }) {
// 提交 CLEAR_CART mutation
commit('CLEAR_CART');
}
},
// 定义获取 state 中数据的方法
getters: {
// 获取购物车中的商品列表
cartItems: state => state.cart,
// 计算购物车中商品的总价
cartTotal: state => state.cart.reduce((total, item) => total + item.price * item.quantity, 0)
}
});
export default store;
三、文章收藏案例
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
favoriteArticles: []
},
mutations: {
ADD_TO_FAVORITES(state, articleId) {
if (!state.favoriteArticles.includes(articleId)) {
state.favoriteArticles.push(articleId);
}
},
REMOVE_FROM_FAVORITES(state, articleId) {
state.favoriteArticles = state.favoriteArticles.filter(id => id !== articleId);
}
},
actions: {
addToFavorites({ commit }, articleId) {
commit('ADD_TO_FAVORITES', articleId);
},
removeFromFavorites({ commit }, articleId) {
commit('REMOVE_FROM_FAVORITES', articleId);
}
},
getters: {
favoriteArticles: state => state.favoriteArticles
}
});
export default store;
四、全局共享参数案例
// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
// 全局主题
theme: 'light',
// 全局语言
language: 'en',
// 字体大小
fontSize: 'medium'
},
mutations: {
// 设置全局主题
SET_THEME(state, theme) {
state.theme = theme;
},
// 设置全局语言
SET_LANGUAGE(state, language) {
state.language = language;
},
// 设置字体大小
SET_FONT_SIZE(state, fontSize) {
state.fontSize = fontSize;
}
},
actions: {
// 设置全局主题的 action
setTheme({ commit }, theme) {
commit('SET_THEME', theme);
},
// 设置全局语言的 action
setLanguage({ commit }, language) {
commit('SET_LANGUAGE', language);
},
// 设置字体大小的 action
setFontSize({ commit }, fontSize) {
commit('SET_FONT_SIZE', fontSize);
}
},
getters: {
// 获取全局主题
theme: state => state.theme,
// 获取全局语言
language: state => state.language,
// 获取字体大小
fontSize: state => state.fontSize
}
});
export default store;