vuex中modules的使用方法--模块化使用vuex

以改文件格式为例

1.index.js


引入vuex,引入模块下的文件one.js,vuex-persistedstate即插件,避免页面刷新state丢失。

代码:

import Vue from 'vue';

import Vuex from 'vuex';

import one from './modules/one';

import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex);

export default new Vuex.Store({

  modules: {

    one

  },

  plugins:[createPersistedState()]

})

2.one.js


定义state,actions,mutations,...并抛出

代码:

const state = {

    info:'hello world',

};

const getters = {

};

const mutations = {

  newVal(state,payload){

    // 修改全局state下的值info

    state.info=payload

  },

};

const actions = {

    changeVal(context, payload){

      //触发mutations里的newVal函数

    context.commit('newVal',payload);

    },

};

export default {

    namespaced: true,

    state,

    getters,

    actions,

    mutations

}

组件中引用修改:

eg:

代码:

<template>

  <div class="div">

    <!-- 页面中引用值,可直接点出 -->

      <div>{{$store.state.one.info}}</div>

    <button @click="change">点击一下修改值</button>

  </div>

</template>

<script>

export default {

  data() {

    return {

    };

  },

  methods: {

    // 修改值

    change() {

      setTimeout(() => {

        // this.$store.dispatch异步操作出发的是commit,然后commmit在提交mutations里的方法

        //this.$store.commit直接操作mutations

        this.$store.dispatch(

          //modules组件化写法,modules下文件名/方法函数名

          "one/changeVal",

          "组件修改全局得值——————你好世界"

        );

      }, 3000);

    }

  },

  created() {

    this.change();

  }

};

</script>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。