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

【uniapp】vue2 使用 Vuex 状态管理

创建store文件夹:store/index.js

// index.js
import Vue from 'vue'
import Vuex from 'vuex'
import address from './modules/address.js'Vue.use(Vuex)const store = new Vuex.Store({modules: {address}
})export default store

创建modules文件夹:modules/address.js

import api from "../../api/api";export default {namespaced: true, // 启用命名空间state: {addressInfo: {}},mutations: {// 用户收货地址SET_DELIVERY_DAARESS(state, detail) {console.log('SET_DELIVERY_DAARESS:', state, detail)state.addressInfo = detail}},actions: {// 获取收货地址详情async fetchGetDeliveryInfo({ commit }, id) {try {const { data: {data} } = await api.getDeliveryInfo(id)commit('SET_DELIVERY_DAARESS', data)return data} catch (err) {console.error(err)throw err}},// 添加收货地址async submitAddDeliveryInfo({ commit }, formData) {try {const { data: {data} } = await api.addDeliveryInfo(formData)return data} catch (err) {console.error(err)throw err}},// 添加收货地址async modifyUpdateDeliveryInfo({ commit }, formData) {try {const { data: {data} } = await api.updateDeliveryInfo(formData)return data} catch (err) {console.error(err)throw err}},},getters: {getDeliveryAddress: (state) => state.addressInfo}
}

main.js 全局挂载

import store from './store'const app = new Vue({store,...App
})

对应页面调用

import { mapState, mapActions } from 'vuex'computed: {// 从名为'address'的 Vuex 模块中映射 addressInfo 状态到组件的计算属性// 将返回的对象混入到 computed 对象中...mapState('address', ['addressInfo'])
},
methods: {// 从'address'模块映射三个 action 方法到组件方法中...mapActions('address', ['fetchGetDeliveryInfo','submitAddDeliveryInfo','modifyUpdateDeliveryInfo']),async showAddress() {try {await this.fetchGetDeliveryInfo({id: this.id})// 如果 addressInfo 有收货地址的数据就填入页面if(this.addressInfo) {this.form = this.addressInfo}} catch (err) {tool.alert(err)}},// 保存地址async saveAddress() {try {// 如果有 id 就更新收货地址,没有就调用新增地址 apiconst api_ = this.id == '' ? this.submitAddDeliveryInfo(this.form) :this.modifyUpdateDeliveryInfo(this.form)const res = await api_} catch (err) {tool.alert(err)}},
}

相关文章:

  • Linux:进程:进程调度
  • 电控---CMSIS概览
  • 关于 AI智能穿戴设备 的详细解析,涵盖其定义、核心技术、功能特性、应用场景、市场现状、挑战与未来趋势,结合典型案例帮助理解其核心价值
  • HTML:表格数据展示区
  • Android studio前沿开发--利用socket服务器连接AI实现前后端交互(全站首发思路)
  • Springboot 自动装配原理是什么?SPI 原理又是什么?
  • 【PGCCC】Postgres MVCC 内部:更新与插入的隐性成本
  • Selenium 获取 Web 页面信息的全指南
  • 【补充篇】Davinci工具要求的dbc格式
  • FortiAI 重塑Fortinet Security Fabric全面智能化进阶
  • ECharts散点图-散点图8,附视频讲解与代码下载
  • 解锁智能制造:PLC远程下载如何让设备运维效率提升10倍?
  • 【C++ Qt】Hello World、初始信号槽、理解对象树 ~~~(通俗易懂 图文并茂)
  • Prometheus thanos架构
  • 【HDFS入门】HDFS高可用性与容错机制深度解析
  • 正则表达式在爬虫中的应用:匹配 HTML 和 JSON 的技巧
  • YOLOv12即插即用---RFAConv
  • 3DS 转 STL 全攻略:传统工具与迪威模型网在线转换深度解析
  • 自动驾驶系列—GLane3D: Detecting Lanes with Graph of 3D Keypoints
  • 2025.04.16【GroupedandStackedbarplot】生信数据可视化技法
  • 当文徵明“相遇”莫奈:苏博将展“从拙政园到莫奈花园”
  • “集团结婚”:近百年前革新婚俗的尝试
  • 半年不到再换岗:伊春市委常委、政法委书记方春彪任伊春森工集团党委书记
  • 世卫大会连续9年拒绝涉台提案
  • 这位中国电影早期的全能奇才,90年前唱响国歌
  • 西浦国际教育创新论坛举行,聚焦AI时代教育本质的前沿探讨