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>
相关推荐
我叫汪枫12 分钟前
前端物理引擎库推荐 - 让你的网页动起来!
前端
百思可瑞教育1 小时前
uni-app 根据用户不同身份显示不同的tabBar
vue.js·uni-app·北京百思可瑞教育·北京百思教育
雾恋5 小时前
最近一年的感悟
前端·javascript·程序员
华仔啊5 小时前
Vue3 的 ref 和 reactive 到底用哪个?90% 的开发者都选错了
javascript·vue.js
A黄俊辉A5 小时前
axios+ts封装
开发语言·前端·javascript
小李小李不讲道理6 小时前
「Ant Design 组件库探索」四:Input组件
前端·javascript·react.js
连合机器人6 小时前
晨曦中的守望者:当科技为景区赋予温度
java·前端·科技
郑板桥307 小时前
tua-body-scroll-lock踩坑记录
前端·javascript
IT古董7 小时前
Vue + Vite + Element UI 实现动态主题切换:基于 :root + SCSS 变量的最佳实践
vue.js·ui·scss
解道Jdon7 小时前
SpringBoot4与Spring7发布:云原生深度进化
javascript·reactjs