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", '登录);
```
相关推荐
Hi_kenyon28 分钟前
VUE3套用组件库快速开发(以Element Plus为例)二
开发语言·前端·javascript·vue.js
Irene199132 分钟前
Vue 3 响应式系统类型关系总结(附:computed、props)
vue.js·props·响应式类型
起名时在学Aiifox33 分钟前
Vue 3 响应式缓存策略:从页面状态追踪到智能数据管理
前端·vue.js·缓存
天若有情67338 分钟前
校园二手交易系统实战开发全记录(vue+SpringBoot+MySQL)
vue.js·spring boot·mysql
计算机程序设计小李同学1 小时前
个人数据管理系统
java·vue.js·spring boot·后端·web安全
李剑一1 小时前
uni-app实现本地MQTT连接
前端·trae
EndingCoder1 小时前
Any、Unknown 和 Void:特殊类型的用法
前端·javascript·typescript
oden2 小时前
代码高亮、数学公式、流程图... Astro 博客进阶全指南
前端
GIS之路2 小时前
GDAL 实现空间分析
前端