vuex使用modules模块化

1、main.js引入

复制代码
//引入vuex
import store from './store'
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>',
  data:function(){
      return{
          wbWinList: []   // 定义的变量,全局参数
      }
  },
})

2、index.js

复制代码
import Vue from 'vue';
import Vuex from 'vuex';
import user from './modules/user'

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        // 定义要传递的数据
        datas: [],
        id:1
    },
    getters: {
      doneTodos (state) {
        state.datas.push({"dade":666})
        return state.datas.length+8
      }
    },
    // 定义修改数据的 mutation
    mutations: {
        setData(state, newDatas) {
          state.id = newDatas;
        }
    },
    // 定义分发数据的 action,用于异步调用mutations
    actions: {
        updateDatas({ commit }, datas) {
          commit('setData', datas);
        }
    },
    // 模块化
    modules:{
      user
    }
});

// 全局使用
// console.log(this.$store.state)
// console.log(this.$store.state.user.id)

export default store;

2、user.js

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

Vue.use(Vuex);

const user = new Vuex.Store({
    state: {
        // 定义要传递的数据
        id:2
    },
    mutations: {
        // 定义修改数据的 mutation
        SET_DATAS(state, newDatas) {
          state.datas = newDatas;
        }
    },
    actions: {
        // 定义分发数据的 action
        updateDatas({ commit }, datas) {
          commit('SET_DATAS', datas);
        }
    }
});

export default user;

3、使用

复制代码
<template>
  <div @click="dadepp">
    {{dades}}
  </div>
</template>

<script>
  export default{
    data(){
      return {
        dades:6666
      }
    },
    methods:{
      dadepp(){
        // 调用getters
        console.log(this.$store.getters.doneTodos)
        console.log(this.$store.state)
        console.log(this.$store.state.user.id)
        // 调用mutations
        this.$store.commit("setData",10)
        console.log(this.$store.state)
        //调用actions
        this.$store.dispatch("updateDatas",20)
        console.log(this.$store.state)
      }
    }
  }
</script>

<style scoped>
  .dade{
    -webkit-box-shadow: 0 2px 0px 0 rgba(0,0,0,.1);
     box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  }
  .draggable-div {
    position: absolute;
  }
</style>
相关推荐
excel1 小时前
HLS TS 文件损坏的元凶:Git 提交与拉取
前端
Aphasia3111 小时前
https连接传输流程
前端·面试
徐小夕1 小时前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github
梦梦代码精1 小时前
2026年PHP开源商城系统实测对比:架构、多商户、商用授权,谁才是真·省心?
vue.js·docker·架构·开源·代码规范
threelab1 小时前
Three.js 物理模拟着色器 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
武器大师721 小时前
lv_binding_js 代码解读
开发语言·javascript·ecmascript
kyriewen2 小时前
CSS Container Queries:彻底告别 @media 写到手软,附 5 个真实布局案例
前端·css·面试
Patrick_Wilson3 小时前
router.replace 之后紧跟 reload,页面为什么无限刷新?
javascript·react.js·浏览器
小小小小宇3 小时前
OpenMemory MCP
前端
和平宇宙3 小时前
AI笔记005. hermes-DeepSeek V4 Pro, 128K上下文引发的探索
前端·人工智能·笔记