1、导出Vuex

import Vuex from 'vuex'

2、定义store

/*状态管理*/
const store = new Vuex.Store({
  state: {
    headerShow: true//是否显示头部
  },
  mutations: {  //不应直接更改state,应通过mutations下的方法来更改状态
    setHeaderShow(state, newValue) {
      this.state.headerShow = newValue;
    }
  }
});

3、将store注入

new Vue({
  store,//把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  render: h => h(App)
}).$mount('#app-box')

4、store状态更改

this.$store.commit('setHeaderShow', true);

5、子组件中获取状态 使用mapState

import { mapState } from 'vuex'

  export default {
    name: 'app',
    components: {
  
    },
    computed: {
      ...mapState({
        headerShow: state => state.headerShow
      })
    },
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-21
  • 2021-10-12
  • 2021-11-07
  • 2021-08-22
  • 2023-04-04
猜你喜欢
  • 2021-07-23
  • 2021-07-09
  • 2022-12-23
  • 2021-09-02
  • 2022-02-24
  • 2022-12-23
相关资源
相似解决方案