vuex从安装到使用的教程

小编 2026-06-05 阅读:1114 评论:0
vuex的安装 npm install vuex --save或cnpm install vue...
vuex的安装
 npm install vuex --save或cnpm install vuex --save
  • 1
main.js引入vuex
import Vue from 'vue'import Vuex from 'vuex'import store from './vuex/store'Vue.use(Vuex)
  • 1
  • 2
  • 3
  • 4
  • 5
vuex的目录结构和store.js的代码

这里写图片描述

store.js的代码(异步和同步的代码均留下两个方法)
import Vue from 'vue'import Vuex from 'vuex'import GLOBAL_CONFIG from '../config/config'import axios from 'axios'import BScroll from 'better-scroll'// import BScroll from '../assets/js/iscroll'Vue.use(Vuex)const menu = {  state: {    mannumber:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,'其它'],    activeindex: null,    nowindex:null,    products: {},    GLOBAL_CONFIG:GLOBAL_CONFIG['GLOBAL_CONFIG']  },  mutations: {    get_product: function (state, products) {        state.products = products;        for(let i = 0; i < state.products.length; i++){            if(state.products[i]['image'] != false && state.products[i]['image'].indexOf(state.GLOBAL_CONFIG['dataImage']) === -1){                state.products[i]['image'] = state.GLOBAL_CONFIG['base64Header'] + state.products[i]['image'];            }else{                state.products[i]['image'] = require("../assets/file.png");            }        }    }  },  actions: {  }}export default new Vuex.Store({    state: {        mastdisplay: false,        supervisory_control:false,        product: {},        countNumber:{},        orderdetail:{},        GLOBAL_CONFIG:GLOBAL_CONFIG['GLOBAL_CONFIG']        },    mutations: {        mastdisplay: function (state,name) {            if(typeof name !== 'string'){                              if(name['name'] == 'mastdisplay' || name['name'] == 'mastspecificat' || name['name'] == 'mastflavour'){                    if(name['product'].hasOwnProperty('specs')){                        for(let i = 0; i < name['product']['specs'].length; i++){                            name['product']['specs'][i]['number'] = 0;                        }                    }                                       state.product = name['product'];                    if(name['name'] === 'mastspecificat'){                        let specificatscroll = new BScroll('.mast-scrollspecificat',{                            scrollY: true,                            click: true                        });                    }                    if(name['name'] === 'mastflavour'){                        let flavouringscroll = new BScroll('.mast-flavouringscroll',{                            scrollY: true,                            click: true                        });                    }                                                        }                name = name['name'];                        }            if(state[name]){                state[name] = false;            }else{                state[name] = true;            }        },        countNumber: function (state,countNumber) {            state.countNumber = countNumber;        },        get_orderdetail: function (state,response) {            state.orderdetail = response;            console.dir(state.orderdetail);        },        hidden_customcount: function (state) {                        if(state.mastload){                state.mastload = false;            }        }    },    components:{    },    modules: {        menu:menu    },    actions: {        get_orderdetail: function (context,company,name) {            axios.post('/point-api-order_detail',{                tableid:company['tableid'],                companyid:company['companyid']            }).then(function(response){                           context.commit('get_orderdetail',response);            }, function(response){                mui.toast('网络错误');            });        },        check_cart: function (context,product) {            axios.post('/point-api-checkcart',{                user_id:product['user_id'],                url:context.state.GLOBAL_CONFIG['WECHAT_API_HOST']+"/wechat/app/index.php?i="+localStorage.i+"&c=entry&do=ShopCart&m=wei_scan_code"            }).then(function(response){                               if(response.hasOwnProperty('error')){                    mui.toast(response['erron']);                    return false;                }else{                    context.commit('set_cart',response);                    // let menuscroll = new BScroll('.mast-cart-content-parent',{                    //     scrollY: true,                    //     click: true                    // });                }             }, function(response){                mui.toast('网络错误');            });        }})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
mutations的使用,可以在mutations里面定义方法,里面的方法为同步操作,方法里的第一个参数是state对象,可操作state对象里定义的属性,第二个参数为传进来的参数,也可不传,在组件里可以直接操作state里的属性,例如:
this.$store.state.mastdisplay 或通过store里的方法改变this.$store.commit('mastdisplay');
  • 1
actions的使用,actions里面的方法用来处理异步操作,调用异步接口后,获取到数据,对state里的属性进行重新赋值,然后在组件里计算该属性的变化
computed: {    orderdetail: function () {      return this.$store.state.orderdetail;    }    mastdisplay: function () {      return this.$store.state.mastdisplay;    }    products: function () {      return this.$store.state.menu.products;    },    product: function () {      return this.$store.state.product;    }  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
在组件里调用actions方法
this.$store.dispatch('get_orderdetail',{        tableid:localStorage.tableid,        companyid:localStorage.companyid      });
  • 1
  • 2
  • 3
  • 4
有时候我们可能会把一个组件分为一个模块,例如上面的代码,我定义了一个menu的模块,那么我需要在modules里面引入这个模块,在组件里操作该模块的属性如下:

this.$store.state.menu.products 

调用该模块的mutations里的方法不需要加上menu.

原文发布时间:
原文作者:一念执着。c
本文来源CSDN博客如需转载请紧急联系作者

版权声明

本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。

热门文章
  • 机房智能化温湿度解决方式之POE供电以太网温湿度传感器

    机房智能化温湿度解决方式之POE供电以太网温湿度传感器
    机房智能化温湿度解决方式之POE供电以太网温湿度传感器 北京盈创力和电子科技有限公司 智能型TCP网口温湿度记录仪 北京IP网络温湿度记录仪厂家,北京盈创力和 北京智能型TCP网口温湿度记录仪IP网络温湿度记录仪是一种新型的基于TCP/IP协议双绞线以太网标准温湿度采集模块,利用它可以实现现场温度值、相对湿度值的采集,同时利用其自身的RJ45通信接口可以方便地和机房监控主机或交换机集线器进行联网。 工作于-40℃~85℃工业级带...
  • Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering

    Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering
    Problem Statement 我们考虑一个具有马尔可夫性质、非线性、非高斯的状态空间模型(State Space Model):对于一个时间序列上的观测结果{yt,t∈N}\\{ y_t , t \\in N \\}{yt​,t∈N},我们认为每个观测结果yty_tyt​的生成依赖于一个无法直接观察的隐变量xt∈{xt,t∈N}x_t \\in \\{x_t , t \\in N \\}xt​∈{xt​,t∈N},即:p(...
  • HTTP状态保持的原理

    HTTP状态保持的原理
    a)在用户登录之后,浏览器返回响应的时候会在响应中添加上cookieb)浏览器接收到cookie之后会自动保存c)当用户再次请求同一服务器中的其他网页的时候,浏览器会自动带上之前保存的cookied)服务接收到请求之后可以请 request 对象中取到cookie 判断当前用户是否登录  Http是无状态的,就是连接时数据互通,关闭后...
  • Hive 系统函数及示例

    Hive 系统函数及示例
    查看所有系统函数 show functions; 函数分类 内置函数【系统函数】 数学函数: floor、round、ceil、cos、log2等 字符串函数: length、reverse、trim、lower、get_json_object、repeat等 收集函数: size 转换函数: cast 日期函数: year、month、datediff、date、date_add等 条件函数: coalesce、case…w...
  • CSRF的原理和防范措施

    CSRF的原理和防范措施
    a)攻击原理:i.用户C访问正常网站A时进行登录,浏览器保存A的cookieii.用户C再访问攻击网站B,网站B上有某个隐藏的链接或者图片标签会自动请求网站A的URL地址,例如表单提交,传指定的参数iii.而攻击网站B在访问网站A的时候,浏览器会自动带上网站A的cookieiv.所以网站A在接收到请求之后可判断当前用户是登录状态,所以...
标签列表