您当前的位置: 首页 > 

梁云亮

暂无认证

  • 1浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

vue3+vuex4 实现不同组件间数据共享

梁云亮 发布时间:2021-04-29 00:04:34 ,浏览量:1

效果

在这里插入图片描述

实现
  • 第一步:修改store/index.ts
import {createStore} from 'vuex'

export default createStore({
  state: {
    count: 1000  // 控制菜单展开与折叠
  },
  mutations: {// 同步方法
    add(state, he) { // 注册事件:唯一修改state.count值的方法
      state.count = state.count + he
      return state.count
    }
  },
  actions: {// 异步方法
    asyncAdd(context, he) { // 该方法需要通过dispatch()调用
      context.commit("add", he)  // 通过commit方法调用add
    }
  },
  modules: {}
})
  • Header.vue

    


import {useStore} from "vuex";
export default {
  setup(): any {
    const store = useStore();
    function toggleSideBar() {
      store.dispatch("asyncAdd", 888);
    }
    return {
      store
    }
  }
}

  • Aside.vue

  ------------ {{store.state.count}}-------------


import { useStore } from 'vuex'
export default {
  setup(): any {
    const store = useStore()
    return {
      store
    }
  }
}

关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0560s