vuex用法心得,实际项目中使用

关于vuex的介绍我相信大家都知道了,而我简单的理解就是存储值的地方。简单来说就是一个箱子,里面可以放自己的数据。(个人的简单理解),好了接下来我们进入正题(已安装vuex)。

第一步:在src下创建store文件夹,然后在store下创建modules文件和index.js。

在这里插入图片描述

第二步:在main.js里引入store,然后new Vue里加上store

import store from './store'

new Vue({
    
    
  el: '#app',
  i18n,
  router,
  store,
  render: h => h(App)
});

第三步:store下的modules文件下新建两个文件dict.js和menu.js

//dict.js文件写法
export default {
    
    
    state: {
    
    
        dictMap: [],  // 数据字典集合
    },
    getters: {
    
       //给页面获取数据时用的方法
        getDictMap(state){
    
    
            return state.dictMap;
        }
    },
    mutations: {
    
      //改变state的值
        setDictMap(state, perms){
    
      // 数据字典集合
            state.dictMap = perms;
        }
    },
    actions: {
    
    
    }
}
//menu.js文件写法
export default {
    
    
    state: {
    
    
        menuList: [],  // 集合
    },
    getters: {
    
       //给页面获取数据时用的方法
        getMenuList(state){
    
    
            return state.menuList;
        }
    },
    mutations: {
    
      //改变state的值
        setMenuList(state, perms){
    
      // 数据字典集合
            state.menuList= perms;
        }
    },
    actions: {
    
    
    }
}

第四步:store文件下的index写法

import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex);
import dict from './modules/dict'
import menu from './modules/menu'
const store = new vuex.Store({
    
    
    modules: {
    
    
        menu: menu,
        dict:dict,
    }
})
export default store

第五步:到这一步基本已经完成了,接下来是从后端取值然后改变state的值,并在组件里使用。

// 比如arr是后端接口返回来的值,获者点击按钮,然后改变state
import store from '@/store'  //在需要改变的js文件里引入
let arr=[
	{
    
    name:'张三',sex:'男'},
	{
    
    name:'李四',sex:'女'}
]
store.commit("setDictMap", arr);  //我这里只改变dict里的值,menuList类似我就不写了

第六步:组件里使用

<template>
    <div class="home">
        <h1>{
    
    {
    
    dictmap}}</h1>
    </div>
</template>
<script>
export default {
    
    
  data () {
    
    
    return {
    
    
    }
  },
  computed:{
    
    
    dictmap:function() {
    
    
      // 通过vuex的getters方法来获取state里面的数据
      return this.$store.getters.getDictMap;
    }
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/weixin_41760500/article/details/106665414