VUEX项目场景

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 {
        // 调用 Vuex 中的 login action,传递用户名和密码
        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>

  • vuex代码
// store/index.js

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;

三、文章收藏案例

// store/index.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    // 存储用户收藏的文章ID列表
    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: {
    // 添加文章到收藏列表的 action
    addToFavorites({ commit }, articleId) {
      commit('ADD_TO_FAVORITES', articleId);
    },
    // 从收藏列表中移除文章的 action
    removeFromFavorites({ commit }, articleId) {
      commit('REMOVE_FROM_FAVORITES', articleId);
    }
  },
  getters: {
    // 获取用户收藏的文章ID列表
    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;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值