vuex的state,actions,getters,mutations的使用

 

1.首先搭建环境

1.1安装node

1.1.1  下载node,下载地址是https://nodejs.org/en/download/,选择windows版本,检查node是否安装成功,node -v

1.2 选择npm或者yarn

1.1.1 如果使用npm,首先安装nrm,安装 npm install -g  nrm 

1.1.2 nrm ls可以查看npm源,使用淘宝镜像nrm use taobao ,然后查看nrm是否切换为淘宝镜像nrm ls

1.1.3 还可以使用cnpm,输入以下命令 npm install -g cnpm --registry=https://registry.npm.taobao.org,查看是否安装成功cnpm -v

1.1.4 如果使用yarn,安装yarn,npm install -g yarn,查看yarn是否安装成功,yarn -v

1.3 安装 vue-cli 脚手架(我使用的yarn)

1.3.1 yarn add  global vue-cli,查看是否安装成功vue -V。(注意:-V中V必须是大写)

2.环境搭建完毕为我们就要开始写项目了

2.1.1创建项目 vue init webpack mytest

2.1.2 根据提示写项目名称,项目描述,项目作者,是否使用vue-router等

2.1.3 为项目添加vuex,cd到项目中,执行命令:yarn add vuex

2.1.4启动项目:yarn run dev

3.分为两种情况,有module和没有mudule

首先看没有module的情况

3.1.1首先我们看下store,state,actions,mutations,getters

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './action'
import getters from './getters'

Vue.use(Vuex)

const state = {
  name: '111', // 用户名
}

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations,
})

 

actions.js

export default {
  setActionName({ state,commit  },name) {
    commit('setMutationName',name)
  },
}

mutations.js

export default {
  //保存用户名
  setMutationName(state, name) {
    state.name = name
  },
}

getters.js

export default {
  gettersName(state) {
    return state.name;
  },
}

3.1.2 接下来来就要操作getters,actions,mutations,state

首先看getters,有四种写法

<template>
  <div>
    <button @click="getUserName()">
      点击获取用户名
    </button>
    <div>获取到的用户名:{{userName}}</div>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'

  export default {
    name: "login",
    data: function () {
      return {
        userName: '',
      }
    },
    methods:{
      getUserName:function(){
        /**
         *  调用getters有四种方法
         *  第一种:this.userName = this.gettersName ,需要在computed中写...mapGetters
         *  第二种:this.userName = this['gettersName'] ,需要在computed中写...mapGetters
         *  第三种:this.userName = this.$store.getters.gettersName,直接调用getters.js中的gettersName方法,不需要mapGetters
         *  第四种:this.userName = this.$store.getters['gettersName'],直接调用getters.js中的gettersName方法,不需要mapGetters
         */
        console.log('没有module的getters:'+JSON.stringify(this.$store.getters))//{"gettersName":"111"}
        this.userName = this.$store.getters['gettersName']
      }
    },
    computed: {
      ...mapGetters([
        'gettersName'
      ])
    },
  }
</script>

<style scoped>

</style>

 

actions有三种写法:

<template>
  <div>
    <input type="number" v-model="userName" placeholder="请输入用户名" />
    <div @click='loginClick()'> 登录</div>
    <div>{{test}}</div>
  </div>
</template>

<script>
  import { mapActions } from 'vuex'
  export default {
    name: "login",
    data:function () {
      return{
        userName:'',
      }
    },
    methods:{
      ...mapActions([
        'setActionName'
      ]),

      loginClick:function () {
        /**
         *  调用actions有三种方法
         *  第一种:this.setActionName(this.userName),需要在methods中写...mapActions
         *  第二种:this['setActionName'](this.userName),需要在methods中写...mapActions
         *  第三种:this.$store.dispatch('setActionName',this.userName),直接调用actions.js中的setActionName方法,不需要mapActions
         */
        this.$store.dispatch('setActionName',this.userName)
      },
    },
    computed:{
      test(){
        return this.$store.state.name;
      }
    }
  }
</script>

<style scoped>

</style>

mutations有一种写法:

<template>
  <div>
    <input type="number" v-model="userName" placeholder="请输入用户名" />
    <button @click='loginClick()'> 登录</button>
    <div>{{test}}</div>
  </div>
</template>

<script>
  export default {
    name: "login",
    data:function () {
      return{
        userName:'',
      }
    },
    methods:{
      loginClick:function () {
        /**
         *  调用mutations有一种方法
         *   this.$store.commit('setMutationName',this.userName)
         */
        this.$store.commit('setMutationName',this.userName)
      },
    },
    computed:{
      test(){
        return this.$store.state.name;
      }
    }

  }
</script>

<style scoped>

</style>

state有四种写法:

<template>
  <div>
    <button @click='loginClick()'> 获取用户名</button>
    <div>获取到的用户名:{{userName}}</div>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  export default {
    name: "login",
    data:function () {
      return{
        userName:'',
      }
    },
    methods:{
      loginClick:function () {
        /**
         *  调用state有四种方法
         *  第一种:this.userName = this.$store.state.name,不需要...mapstate
         *  第二种:this.userName = this.$store.state['name'],不需要...mapstate
         *  第三种:this.userName = this.getName,需要...mapstate
         *  第四种:this.userName = this['getName'],需要...mapstate
         */
        console.log('没有module的state:'+JSON.stringify(this.$store.state))//{"name":"111"}
        this.userName = this['getName']
      },
    },
    computed:{
      ...mapState({
        getName: state => state.name,
      }),
    }
  }
</script>

<style scoped>

</style>

4.再来看看有module的情况:

4.1.1首先我们看在有module的情况的store.js,mod1.js,在mod1中查看actionsOne.js,mutationsOne.js,gettersOne.js,stateOne.js

首先看看store.js

export default new vuex.Store({
  modules:{
    mod1:mod1
  },

  state:{
    address:'西安市'
  },
  getters:{
    getAddress:function (state) {
      return state.address;
    }
  },
  actions:{
    setHaha:function({commit,state},newAddress){
      commit('setAddress',newAddress);
    },
  },
  mutations:{
    setAddress:function (state,newAddress) {
      state.address = newAddress;
    }
  }
});

mod1.js

import stateOne from './stateOne.js'
import mutationsOne from './mutationsOne.js'
import actionsOne from './actionsOne.js'
import gettersOne from './gettersOne'

export default {
    namespaced: true,
    mutations:mutationsOne,
    state:stateOne,
    actions:actionsOne,
    getters:gettersOne
}

 4.1.2 在mod1中查看stateOne.js,gettersOne.js,actionsOne.js,mutationsOne.js

stateOne.js

export default {
  userName:'testName'
}

gettersOne.js 

export default {
  getUserName(state) {
    return state.userName;
  },

  /**
   *  getters 获取到 rootState, rootGetters 作为参数。
   *  rootState和 rootGetter参数顺序不要写反,一定是state在前,getter在后面,这是vuex的默认参数传递顺序, 可以打印出来看一下。
   *  state当前module
   */
  getUserNameTest (state,getters,rootState,rootGetters) {
    return state.userName;
  }
}

actionsOne.js 

export default {//在action中可以进行异步操作。
  // changeName({commit},name){
  //   commit('setName',name);
  // }

  // // actions 中的context参数对象多了 rootState 参数
  // changeName ({commit, rootState},anotherName) {
  //   commit('setName',anotherName);
  // }

  // actions 中的context参数对象多了 rootState 参数
  changeName ({ dispatch, commit, getters, rootGetters },anotherName) {
    dispatch('changeNamedispatch',anotherName);
  },
  changeNamedispatch ({commit, rootState},anotherName) {
    commit('setName',anotherName);
  }
}

mutationsOne.js 

export default {//这里要注意不要在mutations里面进行异步操作
  setName(state,name){
    state.userName = name;
  }
}

4.1.3 接下来看看有module时getters的使用:getters有两种使用方法

<template>
  <div>
    <button @click="getUserName()">
      点击获取用户名
    </button>
    <div>获取到的用户名:{{userName}}</div>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'

  export default {
    name: "login",
    data: function () {
      return {
        userName: '',
      }
    },
    methods:{
      getUserName:function(){
        /**
         *  调用getters有两种方法
         *  第一种:this.userName = this['mod1/getUserName'] ,需要在computed中写...mapGetters
         *  第二种:this.userName = this.$store.getters['mod1/getUserName'],直接调用gettersOne.js中的mod1的getUserName方法,不需要mapGetters
         */
        console.log('有module的getters:'+JSON.stringify(this.$store.getters))//{"getAddress":"西安市","mod1/getUserName":"testName","mod1/getUserNameTest":"testName"}
        this.userName = this.$store.getters['mod1/getUserName'];
      }
    },
    computed: {
      ...mapGetters([
        'mod1/getUserName'
      ])
    },
  }
</script>

<style scoped>

</style>

有module的state:state有四种使用方法

<template>
  <div>
    <button @click='loginClick()'> 获取用户名</button>
    <div>获取到的用户名:{{userName}}</div>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  export default {
    name: "login",
    data:function () {
      return{
        userName:'',
      }
    },
    methods:{
      loginClick:function () {
        /**
         *  调用state有四种方法
         *  第一种:this.userName = this.$store.state.mod1.userName,不需要...mapstate
         *  第二种:this.userName = this.$store.state.mod1['userName'],不需要...mapstate
         *  第三种:this.userName = this.getName,需要...mapstate
         *  第四种:this.userName = this['getName'],需要...mapstate
         */
        console.log('==='+ JSON.stringify(this.$store.state))//{"address":"西安市","mod1":{"userName":"testName"}}
        this.userName = this.getName
      },
    },
    computed:{
      ...mapState({
        /**
         * 下面的方法也可以写为
         *  getName: function(state){
              console.log(JSON.stringify(state))//{"address":"西安市","mod1":{"userName":"testName"}}
              return  state.mod1.userName
           }
         * @param state
         * @returns {*}
         */
        getName: state =>state.mod1.userName//或者getName: state =>state.mod1['userName']
      }),
    }
  }
</script>

<style scoped>

</style>

有module的actions:action有两种使用方法

<template>
  <div>
    <input type="number" v-model="userName" placeholder="请输入用户名" />
    <div @click='loginClick()'> 登录</div>
    <div>{{test}}</div>
  </div>
</template>

<script>
  import { mapActions } from 'vuex'
  export default {
    name: "login",
    data:function () {
      return{
        userName:'',
      }
    },
    methods:{
      ...mapActions([
        'mod1/changeName'
      ]),

      loginClick:function () {
        /**
         *  调用actions有两种方法
         *  第一种:this['mod1/changeName'](this.userName),需要在methods中写...mapActions
         *  第二种:this.$store.dispatch('mod1/changeName',this.userName),直接调用actions.js中的changeName方法,不需要mapActions
         */
        this['mod1/changeName'](this.userName)
      },
    },
    computed:{
      test(){
        return this.$store.state.mod1.userName;
      }
    }
  }
</script>

<style scoped>

</style>

有module的mutations:mutations有一种使用方法

<template>
  <div>
    <input type="number" v-model="userName" placeholder="请输入用户名" />
    <button @click='loginClick()'> 登录</button>
    <div>{{test}}</div>
  </div>
</template>

<script>
  export default {
    name: "login",
    data:function () {
      return{
        userName:'',
      }
    },
    methods:{
      loginClick:function () {
        /**
         *  调用mutations有一种方法
         *   this.$store.commit('setName',this.userName)
         */
        this.$store.commit('mod1/setName',this.userName)
      },
    },
    computed:{
      test(){
        return this.$store.state.mod1.userName;
      }
    }

  }
</script>

<style scoped>

</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值