vue.js中vuex状态管理的实现与模块化

本文采用的前端组件为ElementUI,所以需要在使用vuecli搭建前端工程,后继续安装npm install element-ui,并在main.js中引入

main.js代码:

import Element from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI)

新建存储文件夹用于存放vuex相关组件,其index.js配置vuex的初始主文件,并加载模块中的子模块,下面的模块文件夹存放子模块文件
vue.js中vuex状态管理的实现与模块化_第1张图片

先展示存储/ index.js的代码

import Vue from 'vue'
import Vuex from 'vuex'
//导入vuex的store模块
import moduleOne from './modules/moduleOne'
import services from '../services/index.js'
// import flyio from 'flyio'
Vue.use(Vuex)

// 从环境变量判断当前运行模式
// const debug = process.env.NODE_ENV !== 'production'


const store = new Vuex.Store({
    // strict:debug,                         //设置运行模式
    // plugin:debug ? [createLogger()] : []  //调试模式则加入日志插件
    // 引入modules中的模块
    modules: {
        moduleOne
    },
    //state相当于data
    state: {
        //作者名称
        author: 'FANE',
        address: '江苏南京',
        school: ['北大', '清华'],
        version: '版本1.1',
        loginInfo: {
            name: 'Zhang',
            age: '24'
        },
        count: 1,
        data: ['www']
    },
    //getters相当于computed
    getters: {
        author: state => state.author,
        loginInfo: state => state.loginInfo,
        // address:state => state.address,
        // version:state => state.version,
        // school:state => state.school,
        count: state => state.count,
        data: state => state.data,
    },
    // 只用mjutations修改状态:用于操作state中状态和改变相关数据
    mutations: {
        increment: state => state.count++,
        decrement: state => state.count--,

        dataReceive(state, res) {
            state.data = res
        }

    },
    //actions相当于methods(或者MVC中的Controller),用于操作mutations实现对state中状态的读取,但是actions不会直接对状态做修改
    actions: {
        decrement(context) {
            context.commit('decrement')   // 调用mutations中的decrement
        },
        getBarData(context) {
            // services.apiOne.getBarData.then(res => {
            //     console.log(res)
            // })
            services.apiOne.getBarData(function (res) {
                console.log(`fly获取到结果为:`)
                console.log(res)
            })
        }
    }
})

// 导出store实例对象
export default store

其中的fliyio与axios类似,都是用于前后端通信的组件;

前端代码Helloworld.vue,主要代码注释都放在代码中,方便大家复制走查

<template>
    <div id="helloword">
        <h1 style="font-family: 'AhsanCalligraphyRegular'">Gyosho Test Englishh1>
        <hr>
        <el-row :gutter="20">
            <el-col :span="4">
                <span>getters.author:{{this.author}}span>
                <br>
                <span>state.version:{{this.version}}span>
            el-col>
            <el-col :span="8">
                <span>mapState:{{this.school}}span>
                <br>
                <span>mapState:{{this.address}}span>
            el-col>
            <el-col :span="8">
                <span>mapGetters:{{this.data}}span>
                <br>
                <span>mapGetters:{{this.count}}span>
                <el-button size="small" @click="add()">数字加el-button>
                <el-button size="small" @click="small()">el-button>
            el-col>
        el-row>
        <hr>
        <el-row :gutter="20">
            <el-col :span="6">
                <span>moduleOne.liu:{{this.liu}}span>
                <br>
                <span>computed(loginInfo):{{this.loginInfo}}span>
            el-col>
            <el-col :span="18">
                <el-input v-model="newName" placeholder="请输入内容" style="width:20%">el-input>
                <el-button size="small" @click="changeNewName()">NewNameel-button>
                <el-button size="small" @click="changeNameA()">改成南京el-button>
            el-col>
        el-row>
        <hr>
        <el-row :gutter="10">
            <el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="1"><div class="grid-content bg-purple">响应式布局div>el-col>
            <el-col :xs="4" :sm="6" :md="8" :lg="9" :xl="11"><div class="grid-content bg-purple-light">div>el-col>
            <el-col :xs="4" :sm="6" :md="8" :lg="9" :xl="11"><div class="grid-content bg-purple">div>el-col>
            <el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="1"><div class="grid-content bg-purple-light">div>el-col>
        el-row>
    div>
template>
<script type="text/javascript">
import {mapGetters,mapActions,mapState} from 'vuex'
export default{
     data() {
      return {
          newName:''
      }
    },
    computed:{
         //此处loginInfo是一个对象,默认执行get方法放回当前参数
        loginInfo:{
            get(){
                return this.$store.state.loginInfo.name  //state直接获取
            },
            set(newValue){
                this.$store.state.loginInfo.name = newValue
            }
        },
        version(){
            return this.$store.state.version    //方法一:state直接获取
        },
        author(){
            return this.$store.getters.author   //方法一:getters方法获取
        },

        ...mapState([                           //方法二:mapState获取
            'address',
            'school',
        ]),
        ...mapGetters([                         //方法二:mapGetters获取
            'count',
            'data'
        ]),
        /*moduleOne中的文件*/
        liu(){
            return this.$store.state.moduleOne.liu
        },
    },
    mounted(){
        this.getBarData();
    },
    methods: {
        add(){
            this.$store.commit('increment')  //.commit()方法可以直接调用mutations的increment方法
        },
        small(){
            this.$store.dispatch('decrement')   //方法一:.dispatch()方法调用actions中的方法decrement,间接调用mutations中的decrement
        },
        changeNewName() {
            this.loginInfo = this.newName  // 修改loginInfo内容
            // this.$store.commit('newName',this.newName) 
            this.$store.dispatch('newName', this.newName)
        },
        ...mapActions([                         // 方法二:通过mapActions将actions映射到methods中
            'getBarData',
            'changeNameA'         //changeNameA是来自moduleOne的actions
        ])
    }
}
script>
<style scoped>
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
style>

vuex的模块举个例子为modules/moduleOne.js

import Vue from 'vue'
import services from '../../services/index.js'

const state = {
    liu: 'jingna',
    wei: ['yu', 'ning']
}
const mutations = {
    changeName(state, res) {
        state.liu = res
    },
    newName(state, res) {
        console.log("moduleOne.mutations----newName")
        console.log(res)
        state.liu = res
    }
}

const actions = {
    changeNameA(context) {
        context.commit('changeName', '南京')
    },
    newName(context, params) {
        console.log(`moduleOne.actions=====${params}`)
        context.commit('newName', params)
    }
}

export default {
    state, mutations, actions
}

还有其中的api.js主要存放前端向后端请求的接口api,也是为了代码的模块化,今天加班结束写的博客,感觉自己对vue的理解还是不够,后期会增加对vue前端相关的测试组件等的研究,希望大家多多支持和建议!感谢阅读

你可能感兴趣的:(前端,vue.js,vuex)