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>
相关推荐
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
ew452182 小时前
ElementUI表格表头自定义添加checkbox,点击选中样式不生效
前端·javascript·elementui
suibian52352 小时前
AI时代:前端开发的职业发展路径拓宽
前端·人工智能
画月的亮2 小时前
element-ui 使用过程中遇到的一些问题及解决方法
javascript·vue.js·ui
Moon.92 小时前
el-table的hasChildren不生效?子级没数据还显示箭头号?树形数据无法展开和收缩
前端·vue.js·html
m0_526119402 小时前
点击el-dialog弹框跳到其他页面浏览器的滚动条消失了多了 el-popup-parent--hidden
javascript·vue.js·elementui
垚垚 Securify 前沿站2 小时前
深入了解 AppScan 工具的使用:筑牢 Web 应用安全防线
运维·前端·网络·安全·web安全·系统安全
工业甲酰苯胺5 小时前
Vue3 基础概念与环境搭建
前端·javascript·vue.js
lyj1689975 小时前
el-tree选中数据重组成树
javascript·vue.js·elementui
mosquito_lover16 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt