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", '登录);
```