vuex概括与使用

简介: Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化.详细介绍可以参照官网文档vuex.vuejs.org/zh/


image.png

1.什么是vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化.详细介绍可以参照官网文档vuex.vuejs.org/zh/

下面简单介绍vuex

2.安装和引入

先安装vuex。

1. npm install vuex --save
2. 复制代码

在main.js中引入后即可使用。

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
//vuex使用
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        //全局变量
        count: 31231
    }
})
Vue.config.productionTip = false
    /* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    //vuex必须加入
    store,
    components: { App },
    template: '<App/>'
})
复制代码

3.vuex的使用

<template>
<div>
      老大有{{showData}}
      <HelloWorld2/>
</div>
</template>
<script>
import HelloWorld2 from './HelloWorld2'
import son from './son'
export default {
name: 'HelloWorld',
data () {
  return {
       message2:"",
       cou
    }
},
components:{
  HelloWorld2,
  son
},computed: {
  showData(){
    return this.$store.state.count;
  }
}
}
</script>
复制代码
<template>
<div>
老二有{{$store.state.count}}
</div>
</template>
<script>
export default {
name: 'HelloWorld2',
data() {
      return {
      }
    }
}
</script>
复制代码

4.流程介绍

image.png

如图当没有使用vuex时流程为: view->actions->state->view

image.png

使用了vuex后流程为vuecomponent->(dispatch)actions->(commit)mutations->(mutate)state->(render)->vuecomponent

5.mutation

状态更改,更改 Vuex 的 store 中的状态的唯一方法是提交mutation。Vuex 中的 mutation 非常类似于事件:每个  mutation 都有一个字符串的事件类型 (type)和一个回调函数  (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数。

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
//vuex使用
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        //全局变量
        count: 31231
    },
    //更改状态方法
    mutations: {
        //state为上面的state
        addData(state) {
            // 变更状态
            state.count++
        }
    }
})
Vue.config.productionTip = false
    /* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    //vuex必须加入
    store,
    components: { App },
    template: '<App/>'
})
复制代码

然后执行更改

<template>
<div>
      老大有{{showData}}
      <HelloWorld2/>
      <button type = "button" v-on:click = "changeData">  修改按钮    </button>
</div>
</template>
<script>
import HelloWorld2 from './HelloWorld2'
import son from './son'
export default {
name: 'HelloWorld',
data () {
  return {
       message2:"",
    }
},
components:{
  HelloWorld2,
  son
},computed: {
  showData(){
    return this.$store.state.count;
  }
},
methods: {
  //执行更改
  changeData(event){
      this.$store.commit("addData");
  }
}
}
</script>
复制代码

6.getters过滤

可以限制mutation 比如小于0就不能减少了

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
//vuex使用
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        //全局变量
        count: 0
    },
    //更改状态方法
    mutations: {
        //state为上面的state
        addData(state) {
            // 变更状态
            state.count++
        }
    },
    //过滤
    getters: {
        getState(state) {
            if (state.count >= 5) {
                return 5
            } else {
                return state.count
            }
        }
    }
})
Vue.config.productionTip = false
    /* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    //vuex必须加入
    store,
    components: { App },
    template: '<App/>'
})
复制代码

调用时

<template>
<div>
老二有{{$store.getters.getState}}
</div>
</template>
<script>
export default {
name: 'HelloWorld2',
data() {
      return {
      }
    }
}
</script>
复制代码

7.Action--异步处理

Action 类似于 mutation,不同在于:

Action 提交的是 mutation,而不是直接变更状态。 Action 可以包含任意异步操作。 mutation只能同步处理 main.js。示例如下:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
//vuex使用
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        //全局变量
        count: 0
    },
    //更改状态方法
    mutations: {
        //state为上面的state
        addData(state) {
            // 变更状态
            state.count++
        }
    },
    //过滤
    getters: {
        getState(state) {
            if (state.count >= 5) {
                return 5
            } else {
                return state.count
            }
        }
    },
    actions: {
        //action触发的mutations方法 优势是异步处理
        addData(context) {
            //模拟异步
            setTimeout(() => {
                context.commit('addData')
            }, 1000)
        }
    }
})
Vue.config.productionTip = false
    /* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    //vuex必须加入
    store,
    components: { App },
    template: '<App/>'
})
复制代码

在发送时 应该调用action。

<template>
<div>
      老大有{{showData}}
      <HelloWorld2/>
      <button type = "button" v-on:click = "changeData">  修改按钮    </button>
</div>
</template>
<script>
import HelloWorld2 from './HelloWorld2'
import son from './son'
export default {
name: 'HelloWorld',
data () {
  return {
       message2:"",
    }
},
components:{
  HelloWorld2,
  son
},computed: {
  showData(){
    return this.$store.getters.getState;
  }
},
methods: {
  //执行更改
  changeData(event){
      //操作mutations方法
      //this.$store.commit("addData");
      //应该操作action而不是action触发的mutations方法
      this.$store.dispatch("addData");
  }
}
}
</script>
复制代码

8.Module

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

如路由可以分割文件 不在main.js中放入vuex 新建store/index.js

//vuex使用
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
    state: {
        //全局变量
        count: 0
    },
    //更改状态方法
    mutations: {
        //state为上面的state
        addData(state) {
            // 变更状态
            state.count++
        }
    },
    //过滤
    getters: {
        getState(state) {
            if (state.count >= 5) {
                return 5
            } else {
                return state.count
            }
        }
    },
    actions: {
        //action触发的mutations方法 优势是异步处理
        addData(context) {
            //模拟异步
            setTimeout(() => {
                context.commit('addData')
            }, 1000)
        }
    }
})
复制代码

修改main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
    /* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    //vuex必须加入
    store,
    components: { App },
    template: '<App/>'
})
复制代码

我们还能把main.js中的state拿出 新建store/state.js

export default {
    count: 0
}
复制代码

然后index.js可以改成

//vuex使用
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
Vue.use(Vuex)
export default new Vuex.Store({
    state: state,
    //更改状态方法
    mutations: {
        //state为上面的state
        addData(state) {
            // 变更状态
            state.count++
        }
    },
    //过滤
    getters: {
        getState(state) {
            if (state.count >= 5) {
                return 5
            } else {
                return state.count
            }
        }
    },
    actions: {
        //action触发的mutations方法 优势是异步处理
        addData(context) {
            //模拟异步
            setTimeout(() => {
                context.commit('addData')
            }, 1000)
        }
    }
})


相关文章
|
1天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8058 2
|
10天前
|
域名解析 人工智能 Linux
|
20天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
18292 63
|
18天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
4天前
|
人工智能 安全 网络安全
|
2天前
|
人工智能 弹性计算 安全
阿里云 码上2027 AI coding 嘉年华
阿里云“码上2027”AI Coding嘉年华于2026年12月2—3日在上海西岸艺术中心举行,聚焦AI Coding从单点提效迈向企业级研发体系升级。发布Qwen4-max模型、QBot智能协作、AgentCore平台等重磅成果,并推出ECS云服务器特惠(200Mbps流量月付40元起)。
775 0
|
8天前
|
云安全 数据采集 人工智能
|
9天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1478 5
|
15天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2608 8
|
20天前
|
弹性计算 人工智能 API
Codex超详细入门指南(下载·安装·登录·上手,全版本覆盖,2026最新版)
建议收藏本教程,2026 全年各版本更新随时回来查阅。如果你在搭建过程中遇到任何问题,欢迎结合 阿里云工单系统 提交技术支持请求,或在 阿里云开发者社区 搜索 Codex 相关话题交流。 祝你编码愉快,效率翻倍!
4075 22