了解Vuex方法的使用初级篇

1,363 阅读9分钟

简介

        Hellow,大家好啊有一周不见了呢,这周想要讲一讲Vuex方法的使用,不是state和mutations这么简单了,大家可以把这个当成是入门级教学来看,接下来我们进入正题。

了解Vuex的modules

        有人可能问了问什么要了解Vuex的modules,下面我来讲讲modules是什么,当项目越来越大的时候,单个 store 文件,肯定不是我们想要的, 所以就有了模块化这个概念。首先我们看看怎么使用modules。

        安装Vuex

npm install vuex --save
cnpm install vuex --save

        创建stroe文件,里面新建index.js里面这样写

// 引入vue 和 vuex
import Vue from 'vue'
import Vuex from 'vuex'

// 这里需要use一下,固定写法,记住即可
Vue.use(Vuex)

export default new Vuex.Store({
    //模块化vuex所以说就是相当于模块化让store拆分成多个互不干扰
    modules: {
        people_vuex:people_vuex
    }
});

        这样一个简单的模块就加载加载进来了,我们在modules里引入了people_vuex模块

Vuex modules模块引入后其他方法的引入及使用方法

        Vuex modules引入成功之后这时还不能着急使用还得至少引入state才行,下面我们看看怎么引入state

        引入state之前先创建一个新的js文件命名为people_vuex.js,之后再index.js中引入这个js文件

// 引入vue 和 vuex
import Vue from 'vue'
import Vuex from 'vuex'
//看这里在这里引入people_vuex.js
import people_vuex from './people_vuex'

// 这里需要use一下,固定写法,记住即可
Vue.use(Vuex)

export default new Vuex.Store({
    //模块化vuex所以说就是相当于模块化让store拆分成多个互不干扰
    modules: {
        people_vuex:people_vuex
    }
})

        创建一个文件还是不行还要创建一个people_state.js文件,不过在这之前还是先补齐people_vuex.js的内容。

import people_state from './people_state'
export default {
    state:people_state,
}

        这样我们就看到了people_vuex.js引入state模块的people_state.js,这里大家大概就知道我想说什么了吧,通过modules引入模块people_vuex之后在people_vuex.js里面就是people_vuex这块的内容,一个独立的模块就这样建起来了,之后的引入我们在下面再进行讲解,现在先补充state的内容。

        people_state.js里面这样写

const people_state={
    name:'hellow'
}

// 使用 export default 封装,让外部可以访问
export default people_state;

        下一部全局引入Vuex入口文件,在main.js里引入。

//引用vuex文件入口
import store from './store/index'

new Vue({
    ...
        store:store,
    ...
})

        之后新建一个a.vue里面这样去写

<template>
    <div>
      {{getCoin}}
    </div>
</template>

<script>
export default {
    ...
        computed:{
            getCoin(){
              return this.$store.state.people_vuex.coin
            }
        }
    ...
},
created(){
    console.log(this.$store.state.people_vuex.coin);
}
</script>

        通过this.$store查找到我们存的数据记住两点,一点是必须通过return的方式才能取到我们想要的值,要不然则会报错,第二点则是想要找到我们通过模块存的store只能通过我们设置的模块名进行查找,另外补充一句为了方便我在下面打印了我们取到的数据。大家可以跑起来看看。

        下面我们讲讲mutations,之前我们的文章中有过简介mutations的使用方法,如果大家有兴趣可以去看看,不过这次有些略微不同。

        Vuex与Busemit结合使用浅谈Vuex使用方式

        首先在store文件夹里创建people_mutations.js

import people_state from './people_state'
const people_mutations={
    updateCoin (people_state) {
            people_state.coin = 'newName'
    }
}
export default people_mutations;

        之后在people_vuex.js引用people_mutations.js

import people_state from './people_state'
import people_mutations from './people_mutations'
export default {
    state:people_state,
    mutations:people_mutations
}

        第三步就是在vue文件下使用了在a.vue文件下这样写

<template>
    <div>
      {{getCoin}}
      <button v-on:click="changeCoin()">点击我切换</button>
    </div>
</template>

<script>
export default {
    ...
        computed:{
            getCoin(){
              return this.$store.state.people_vuex.coin
            }
        },
        methods:{
            changeCoin () {
                this.$store.commit('updateCoin');
            }
        }
    ...
},
created(){
    console.log(this.$store.state.people_vuex.coin);
}
</script>

        这样大家就可以看到具体的效果了。

正题

        说了这么多大家一定会奇怪为什么我现在才开始正题,因为我这篇是Vuex的初级使用篇所以前面还是讲的细一点,以免初学者不会前面的几步,那我们就讲不了后面的了。好了废话不多说开始正题。

        首先我们还是以一个demo为例,因为我是金融区块链这块的所以对于币种的接触还是比较多的,比如比特币,莱特币,以太币等等,但是它们之间的单位并没有共通之处,比如比特币1比特币等于是1亿聪,又比如以太币的单位是1莱特币等于1e18Wei就是1后面18个零,那么如果小伙伴们有兴趣可以去了解一下,接下来进入模拟需求部分,现在需求提出想要将后端传回来的数字使用逗号分隔开,这样的方式显示金额之后在转账时把后端传过来的数据再次发送给后端当然这之前还是需要改变一下数值的为了大家能看得清,那么我们的思路就有了首先是接收后端的数据,之后进行数据处理,然后放在页面上展示,在这之后会有一个变动的数值,最后将数值使用异步方式发送给后端,整个流程完毕。

        第一步回顾我们上面讲的东西,不过需要做一些小变动,我会在下面代码中注释的,注意看。

//index.js这里没什么需要特别讲解的直接跳过也行
// 引入vue 和 vuex
import Vue from 'vue'
import Vuex from 'vuex'

// 这里需要use一下,固定写法,记住即可
Vue.use(Vuex)

export default new Vuex.Store({
    //模块化vuex所以说就是相当于模块化让store拆分成多个互不干扰
    modules: {
        people_vuex:people_vuex
    }
});
//people_state.js这里一会会添加getters数据处理和actions异步提交两个方法
import people_state from './people_state'
import people_mutations from './people_mutations'
export default {
    state:people_state,
    mutations:people_mutations
}
//people_state.js这里把coin清空就行方便我们接收后端传回来的值
const people_state={
    coin: ''
}
// 使用 export default 封装,让外部可以访问
export default people_state;
//people_mutations.js这里是一个小重点注意看我下面的注释
import people_state from './people_state'
const people_mutations={
    //这里是改变数值的方法
    updateCoin (people_state) {
        people_state.coin = '1000000100000100001000100101'
    },
    //这里注意mutations里面是可以传入两个值的注意前面一个值我们不用管重点是后面的值这个值就是后端传回来的东西了,这里要划重点
    changeCoin (people_state,coin){
        people_state.coin = coin
    }
};
export default people_mutations;
//a.vue这里的使用方法也会略有不同注意
<template>
    <div>
      {{getCoin}}
      <button v-on:click="changeCoin()">点击我切换</button>
    </div>
</template>

<script>
export default {
    ...
        computed:{
            getCoin(){
              return this.$store.state.people_vuex.coin
            }
        },
        methods:{
            changeCoin () {
                this.$store.commit('updateCoin');
            }
        },
        //注意这里这里我们模拟后端传入的值在commit的第二个参数就是后端传入的值
         initializeCoin () {
          this.$store.commit('changeCoin','1001000100001000001000001');
      },
      created(){
        this.initializeCoin();
      }
    ...
},
created(){
    console.log(this.$store.state.people_vuex.coin);
}
</script>

        前期的准备工作好了,接下来我们使用getters处理数据。首先新建people_getters.js

import people_state from './people_state'
const people_getters={
    
}
export default people_getters

        数据处理之前讲几点,首先是getters方法我们可以看成是对数据的二次处理,我们拿到数据后想要怎么处理就随便了,但是一个处理方法里面的处理方式是固定的,比如现在我想处理钱币以逗号分隔开,那么这个方法就只能处理与这个类似的东西,但是是getters还给我们了另外一个选择就是在二次处理过后的数据再次添加一个方法对数据进行三次处理,这里就不过多进行赘述了,方法同样是传入两个参数,其中第二个参数是之前二次处理过的数据,下面贴一个代码大家看看就行

//理解就是对数据进行二次处理,至于处理方式就要看自己了,处理之后的,这里要注意处理的方法是固定的不过不要担心,这个函数是可以传入下一个getters里面进行处理的,Getters还将获得其他getter作为第二个参数
xxxx: (a, b) => {
    return b.c.length
}

        上面的仅作为参考,下面我要讲的是模拟需求中使用getters,废话不多说看代码。

        在people_vuex.js中引入people_getters.js

import people_state from './people_state'
import people_mutations from './people_mutations'
import people_getters from './people_getters'
export default {
    state:people_state,
    mutations:people_mutations,
    getters:people_getters
}

        第二步写一个数据处理方法,就是我们讲的金额逗号间隔。

import people_state from './people_state'
const people_getters={
    getReverseCoin: people_state => {
        //这个方法大家可以看看,是处理方式,传入钱币值之后进行处理
        if(people_state.coin)
        {
            people_state.coin = people_state.coin.toString().replace(/\$|\,/g,'');
            if(''==people_state.coin || isNaN(people_state.coin)){return 'Not a Number ! ';}
            var sign = people_state.coin.indexOf("-")> 0 ? '-' : '';
            var cents = people_state.coin.indexOf(".")> 0 ? people_state.coin.substr(people_state.coin.indexOf(".")) : '';
            cents = cents.length>1 ? cents : '' ;
            people_state.coin = people_state.coin.indexOf(".")>0 ? people_state.coin.substring(0,(people_state.coin.indexOf("."))) : people_state.coin ;
            if('' == cents){ if(people_state.coin.length>1 && '0' == people_state.coin.substr(0,1)){return 'Not a Number ! ';}}
            else{if(people_state.coin.length>1 && '0' == people_state.coin.substr(0,1)){return 'Not a Number ! ';}}
            for (var i = 0; i < Math.floor((people_state.coin.length-(1+i))/3); i++)
            {
                people_state.coin = people_state.coin.substring(0,people_state.coin.length-(4*i+3))+','+people_state.coin.substring(people_state.coin.length-(4*i+3));
            }
            return (sign + people_state.coin + cents);
        }
        //这里注意必须return,不然会报错,这里就是处理过之后的数据了
        return people_state.coin
    },
};
export default people_getters

        下面我们看看怎么使用getters方法,在下面我会对改变的地方进行标注。

<template>
    <div>
      {{getCoin}}
      <button v-on:click="changeCoin()">点击我切换</button>
    </div>
</template>

<script>
export default {
    ...
        computed:{
            getCoin(){
              //这里就是变化的地方了使用$store.getters取到我们刚才定义的getReverseCoin方法
              return this.$store.getters.getReverseCoin
            }
        },
        methods:{
            changeCoin () {
                this.$store.commit('updateCoin');
                 // 在这里打印出来明显就可以看到处理过后的效果,就算使用mutations方法之后改变数值也是一样会被处理
                 console.log(this.$store.getters.getReverseCoin);
            }
        },
         initializeCoin () {
          this.$store.commit('changeCoin','1001000100001000001000001');
      },
      created(){
        this.initializeCoin();
      }
    ...
},
created(){
    console.log(this.$store.state.people_vuex.coin);
}
</script>

        之前上面讲过getters可以传入两个参数,第二个参数是之前处理过的数据再次进行三次处理,但是这里就贴一下使用方法,具体就不写的这么细了,大家有兴趣可以去看看官方文档。

        Vuex Getter官方文档

getters: {
  // 这里的方法就是把第二个参数做处理之后抛出,这里就不细讲了。
  doneTodosCount: (state, xxxx) => {
    return xxxx.a.length
  }
}

        既然前面的步骤都走完了,我们就应该走最后一步了,那就是actions异步方法,首先先看看官方介绍。

        Action 提交的是 mutation,而不是直接变更状态。

        Action 可以包含任意异步操作。

        这里注意了上面说的 Action可以包含任意异步操作,包括异步请求之类的都可以包含进去,这里我们就不讲异步请求只是讲讲Action的使用方法,不过也大概可以理解为在Action里面写一个请求方法这样的,废话不多说,直接上代码。

        首先还是先新建一个people_actions.js,这里注意一下下面的注释

//这里与以往的其他使用方式稍微有些不同,这里引入了两个js一个是一直都有引入的people_state.js,另一个是people_mutations.js这个就是我想要模拟的方法了,在改变state里面的数值之后直接就可以请求。
import people_mutations from './people_mutations'
import people_state from './people_state'
//使用异步方法调用mutations
const people_actions={
    updateCoinSubmit ({ commit }) {
        setTimeout(() => {
            //这里的使用方法和vue文件里的方法一样不过就是没有这么多的引用前缀了直接使用commit就可以对mutations里面的方法进行调用。
            commit('updateCoin')
            //这里我特地把改变之后的数值打印出来了,数值是没有进行过处理的,符合我们之前说的条件直接可以传回后端使用。
            console.log(people_state.coin)
        }, 1000)
    }
};
export default people_actions

        之后在people_vuex.js中引用就行

import people_state from './people_state'
import people_mutations from './people_mutations'
import people_getters from './people_getters'
import people_actions from './people_actions'
export default {
    state:people_state,
    mutations:people_mutations,
    getters:people_getters,
    actions:people_actions
}

        最后在vue文件中引用就行,这里大家还是注意一下我的注释,改变虽说不是很大但是还是得注意起来才行,下面贴代码。

<template>
    <div>
      {{getCoin}}
      <button v-on:click="changeCoin()">点击我切换</button>
    </div>
</template>

<script>
export default {
    ...
        computed:{
            getCoin(){
              return this.$store.getters.getReverseCoin
            }
        },
        methods:{
            changeCoin () {
                //这里注意了actions的调用方法和mutations还是不同的,mutations使用commit就可以对其方法进行调用,然而mutations只能使用dispatch进行调用,所以这里大家注意一下就行了。
                this.$store.dispatch('updateCoinSubmit');
                console.log(this.$store.getters.getReverseCoin);
            }
        },
         initializeCoin () {
          this.$store.commit('changeCoin','1001000100001000001000001');
      },
      created(){
        this.initializeCoin();
      }
    ...
},
created(){
    console.log(this.$store.state.people_vuex.coin);
}
</script>

        其实actions还有一个分发 Action使用store.dispatch触发,这里就不讲了,同样有兴趣的小伙伴可以去官网看看,到这里我们需要讲的Vuex的使用方法就讲完了,但是这个依旧是很浅的使用方式,不会涉及过多深入的东西,下周我将带领大家进一步深入Vuex理解里面的更多东西。

        下面是本期的全部代码,贴出来大家了解一下。

//a.vue
export default {
    ...
        computed:{
            getCoin(){
              return this.$store.getters.getReverseCoin
            }
        },
        methods:{
            changeCoin () {
                this.$store.dispatch('updateCoinSubmit');
                console.log(this.$store.getters.getReverseCoin);
            }
        },
         initializeCoin () {
          this.$store.commit('changeCoin','1001000100001000001000001');
      },
      created(){
        this.initializeCoin();
      }
    ...
},
created(){
    console.log(this.$store.state.people_vuex.coin);
}
</script>
//main.js
import store from './store/index'

new Vue({
    ...
        store:store,
    ...
})
//index.js
import Vue from 'vue'
import Vuex from 'vuex'
import people_vuex from './people_vuex'
Vue.use(Vuex)
export default new Vuex.Store({
    modules: {
        people_vuex:people_vuex
    }
})
//people_vuex.js
import people_state from './people_state'
import people_mutations from './people_mutations'
import people_getters from './people_getters'
import people_actions from './people_actions'
export default {
    state:people_state,
    mutations:people_mutations,
    getters:people_getters,
    actions:people_actions
}
//people_state.js
const people_state={
    coin: ''
};
export default people_state;
//people_mutations.js
import people_state from './people_state'
const people_mutations={
    updateCoin (people_state) {
        people_state.coin = '1000000100000100001000100101'
    },
    changeCoin (people_state,coin){
        people_state.coin = coin
    }
};
export default people_mutations;
//people_getters.js
import people_state from './people_state'
const people_getters={
    getReverseCoin: people_state => {
        if(people_state.coin)
        {
            people_state.coin = people_state.coin.toString().replace(/\$|\,/g,'');
            if(''==people_state.coin || isNaN(people_state.coin)){return 'Not a Number ! ';}
            var sign = people_state.coin.indexOf("-")> 0 ? '-' : '';
            var cents = people_state.coin.indexOf(".")> 0 ? people_state.coin.substr(people_state.coin.indexOf(".")) : '';
            cents = cents.length>1 ? cents : '' ;
            people_state.coin = people_state.coin.indexOf(".")>0 ? people_state.coin.substring(0,(people_state.coin.indexOf("."))) : people_state.coin ;
            if('' == cents){ if(people_state.coin.length>1 && '0' == people_state.coin.substr(0,1)){return 'Not a Number ! ';}}
            else{if(people_state.coin.length>1 && '0' == people_state.coin.substr(0,1)){return 'Not a Number ! ';}}
            for (var i = 0; i < Math.floor((people_state.coin.length-(1+i))/3); i++)
            {
                people_state.coin = people_state.coin.substring(0,people_state.coin.length-(4*i+3))+','+people_state.coin.substring(people_state.coin.length-(4*i+3));
            }
            return (sign + people_state.coin + cents);
        }
        return people_state.coin
    },
};
export default people_getters
//people_actions.js
import people_mutations from './people_mutations'
import people_state from './people_state'
const people_actions={
    updateCoinSubmit ({ commit }) {
        setTimeout(() => {
            commit('updateCoin')
            console.log(people_state.coin)
        }, 1000)
    }
};
export default people_actions

        最后是写本文章之前借鉴的其他文章目录了解一下。

        Vuex 官网

        vuex其实超简单,只需3步

        vuex其实超简单,只需3步

        JS-为金额添加千分位逗号分割符

后记

        这期文章虽说文字有些啰嗦,但是我还是希望你们能看到这里,我想说的是新人可以看这篇文章入门,而老人们可以温习一下,其实知识是永无止境的,我们在寻求知识的同时不应该把以前的东西丢下或者停止学习,三省吾身,这就是我要说的,谢谢大家观看,下周再见。