当前位置: 首页 > news >正文

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.jsimport 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;

三、文章收藏案例

// store/index.jsimport 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: {// 添加文章到收藏列表的 actionaddToFavorites({ commit }, articleId) {commit('ADD_TO_FAVORITES', articleId);},// 从收藏列表中移除文章的 actionremoveFromFavorites({ commit }, articleId) {commit('REMOVE_FROM_FAVORITES', articleId);}},getters: {// 获取用户收藏的文章ID列表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;
http://www.lryc.cn/news/297616.html

相关文章:

  • vue+springboot前后端视频文件等的上传与展示(基于七牛云)
  • ClickHouse--02--安装
  • 【学网攻】 第(23)节 -- PPP协议
  • Rust方法自动解引用测试,总结和补充
  • 备战蓝桥杯---动态规划之经典背包问题
  • Go语言每日一练——链表篇(八)
  • 跟着cherno手搓游戏引擎【23】项目维护、2D引擎之前的一些准备
  • Redis(十三)缓存双写一致性策略
  • 7 scala的类构造器
  • 如何在 Mac 上恢复永久删除的文件:有效方法
  • Web后端开发:事务与AOP
  • [word] word如何打印背景和图片? #微信#其他#经验分享
  • Maven - 编译报错:程序包 XXX 不存在(多模块项目)
  • Vue事件中如何使用 event 对象
  • Golang GC 介绍
  • 决策树之scikit-learn
  • Python爬虫之关系型数据库存储#5
  • ANSI Escape Sequence 下落的方块
  • Vagrant 虚拟机工具基本操作指南
  • 中年低端中产程序员从西安出发到海南三亚低成本吃喝万里行:西安-南宁-湛江-雷州-徐闻-博鳌-陵水-三亚-重庆-西安
  • 企业级Spring boot项目 配置清单
  • WordPress函数wptexturize的介绍及用法示例,字符串替换为HTML实体
  • 【Iceberg学习三】Reporting和Partitioning原理
  • 肯尼斯·里科《C和指针》第12章 使用结构和指针(1)链表
  • Xray 工具笔记
  • Linux环境下配置HTTP代理服务器教程
  • JavaEE作业-实验三
  • K8S容器挂了后重启状态正常,但应用无法访问排查处理
  • 问题:老年人心理健康维护与促进的原则为________、________、发展原则。 #媒体#知识分享
  • 【超高效!保护隐私的新方法】针对图像到图像(l2l)生成模型遗忘学习:超高效且不需要重新训练就能从生成模型中移除特定数据