vue x 状态管理

1:创建store/index

复制代码
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  // 全局数据对象(存储在state内)
  headerTitle: '爱智住Ai'
}
// 同步方法,最终修改全局对象数据
const mutations = {
  headerTitle(state, newVal) {
    state.headerTitle = newVal
  }
}
// 可编写异步方法,写一些相关逻辑,调用mutations方法修改全局对象数据
const actions = {
  headerTitle(state, newVal) {
    state.commit('headerTitle', newVal)
  }
}

export default new Vuex.Store({
  state,
  mutations,
  actions
})

2:main.js 引入挂载

复制代码
import store from './store'
new Vue({
  el: '#app',
  router,
  store,
  r

ender: h => h(App)

})

3:获取状态

复制代码
this.$store.state.headerTitle

4:修改状态

4.1组件方法触发 (dispatch)-> 指派store的actions执行方法 (commit)-> 提交至mutations执行(修改全局值)

复制代码
this.$store.dispatch('headerTitle', '登录')

4.2   组件中的方法直接来commit提交让store里的mutations方法执行

```
        this.$store.commit("headerTitle", '登录);
```
相关推荐
codeGoogle9 分钟前
Vue3 UIKit 实战:把聊天、会话、主题和移动端适配全部封装好
前端
大龄秃头程序员41 分钟前
iOS Method Swizzling 的工程化实践:如何处理多重交换与第三方冲突
前端
liangshanbo12151 小时前
Webpack 文件指纹面试题整理
前端·webpack·node.js
xieter1 小时前
【技术精选】Node.js 核心事件循环机制与异步 I/O 深度剖析 (2026-10-02)
前端·javascript
计算机魔术师1 小时前
Ethan Mollick 谈点与群:智能体自组织为何让管理假设失效
前端
想吃火锅10051 小时前
【leetcode】238.除了自身以外数组的乘积js
javascript·算法·leetcode
故七月2 小时前
GEO 信源评估体系:如何判断一条网页信源能否被大模型采信
前端·网络·人工智能
liangshanbo12152 小时前
Webpack 常见 Plugin 面试题
前端·webpack·node.js
xxwl5852 小时前
vue3的入门学习
前端·vue.js·学习
用户847172102842 小时前
.shot 文件格式规范
前端·后端