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.jsimport 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: {// 添加商品到购物车的 actionaddToCart({ commit }, product) {// 提交 ADD_TO_CART mutation,传递商品信息commit('ADD_TO_CART', product);},// 从购物车中移除商品的 actionremoveFromCart({ commit }, productId) {// 提交 REMOVE_FROM_CART mutation,传递商品 IDcommit('REMOVE_FROM_CART', productId);},// 更新购物车中商品数量的 actionupdateQuantity({ commit }, payload) {// 提交 UPDATE_QUANTITY mutation,传递商品 ID 和新的数量commit('UPDATE_QUANTITY', payload);},// 清空购物车的 actionclearCart({ commit }) {// 提交 CLEAR_CART mutationcommit('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.jsimport 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: {// 设置全局主题的 actionsetTheme({ commit }, theme) {commit('SET_THEME', theme);},// 设置全局语言的 actionsetLanguage({ commit }, language) {commit('SET_LANGUAGE', language);},// 设置字体大小的 actionsetFontSize({ commit }, fontSize) {commit('SET_FONT_SIZE', fontSize);}},getters: {// 获取全局主题theme: state => state.theme,// 获取全局语言language: state => state.language,// 获取字体大小fontSize: state => state.fontSize}
});export default store;