Vuex(Store)的基本使用

2020-04-28  本文已影响0人  辉夜真是太可爱啦
vuex可以理解为整个Vue程序中的全局变量,但他和以前概念中的全局变量又有所不同,他也是响应式的,而且,你不能直接修改vuex中的变量,只能通过显式地commit=>mutation来进行数据的改变。
首先在src文件目录下新建store文件夹,在store文件夹中新建module文件夹以及index.js,然后在module中新建自己的功能模块的js文件,例如我这边新建了一个user.js,专门存放用户相关的全局变量,所以目录如下
├─ src    //主文件
|  ├─ store       //vuex全局变量文件夹
|  |  |- index.js      //store主文件
|  |  └─ module     //store模块文件夹
|  |  |  └─ user.js      //存放user相关的全局变量
|  ├─ main.js 

接下来,在相应的文件夹中写入以下内容

//index.js
import Vue from 'vue'
import Vuex from 'vuex'

import user from './modules/user'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    user
  }
})

//user.js
const state = ({      //state里面存放的是变量,如果你要注册全局变量,写这里
  username:'',   
});

const getters = {                //getters相当于是state的计算属性,如果你需要将变量的值进行计算,然后输出,写这里
  fullName(state){
    return state.username + '大王';
  }}
;

const mutations = {       //修改store中的变量的方法,如果你要改变变量的值,就写这里
  SET_username(state, value) {
    state.username = value;
  },
};

const actions = {            //actions提交的是mutations,相当于就是改变变量的方法的重写,但是,actions是可以进行异步操作的
  setUsername(content) {
    content.commit('SET_username');
  }
};

export default{
  namespaced:true,
  state,
  getters,
  mutations,
  actions
};

//main.js
import Vue from 'vue'
import App from './App'
import store from './store/index'

new Vue({
  el: '#app',
  store,
  components: { App },
  template: '<App/>'
});
在上面的代码中,已经实现了vuex的模块化,定义State,Getter,Mutation,Action等所有基本的功能。

页面中的使用

  • state => this.$store.state.user.username
  • getter => this.$store.getters.user.fullName
  • mutation => this.$store.commit('user/SET_username','cooldream') 此时的username值为cooldream
  • mutation => this.$store.dispatch('user/SET_username') action未找到传值的方法
<script>
  import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'

    export default {
        name: "Parent",
        computed:{
            ...mapState({
                username:state=>state.user.username   //用this.username即可访问
            }),
            ...mapGetters({
                fullName:'user/fullName'    //用this.fullName可访问
            })
        },
        methods:{
          ...mapMutations({
              setName:'user/SET_username'    //this.setName('cooldream');   即可将值变为cooldream
          }),
          ...mapActions({
              asyncSetName:'user/setUsername'    //this.asyncSetName();   即可调用commit('user/setUsername')
          })
        },
    }
</script>
上一篇 下一篇

猜你喜欢

热点阅读