vuex学习及使用
什么是vuex?
在SPA单页面组件的开发中vuex称为状态管理;简单的理解就是你在state中定义了一个数据之后,你可以在所在项目中的任何一个组件里进行获取、进行修改,并且你的修改可以得到全局的响应变更。
在vue中使用vuex,首先要安装:
npm install vuex --save
然后再src文件目录下新建一个名为store的文件夹,为方便引入并在store文件夹里新建一个index.js,里面的内容如下:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store=new Vuex.Store(); export default store;
接下来,在main.js里面引入store,然后再全局注入一下,这样一来就可以在任何一个组件里面使用this.$store了:
import store from './store'//引入store
new Vue({
el:'#app',
router,
store,//使用store
template:'<App/>',
components:{App}
})
说了上面的前奏之后,接下来就是纳入正题了,就是开篇说的state的玩法。回到store文件的index.js里面,我们先声明一个state变量,并赋值一个空对象给它,里面随便定义两个初始属性值;然后再实例化的Vuex.Store里面传入一个空对象,并把刚声明的变量state扔里面:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state={//要设置的全局访问的state对象
showFooter:true,
changableNum:0
//要设置的初始属性值
};
const store=new Vuex.Store({
state
}); export default store;
实际上做完上面的三个步骤后,你已经可以用this.$store.state.showFooter或this.$store.state.changebleNum在任何一个组件里面获取showFooter和changebleNum定义的值了,但这不是理想的获取方式;vuex官方API提供了一个getters,和vue计算属性computed一样,来实时监听state值得变化(最新状态),并把它扔进Vuex.Store里面,具体看下面代码:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state={//要设置的全局访问的state对象
showFooter:true,
changableNum:0
};
const getters={//实时监听state值得变化(最新状态)
isShow(state){//方法名随意,主要是来承载变化的showFooter的值
return state.showFooter
},
getChangedNum(){//方法名随意,主要是来承载变化的changebleNum的值
return state.changebleNum
}
};
const store=new Vuex.Store({
state,
getters
});
export default store;
光有定义的state的初始值,不改变它不是我们想要的需求,接下来要说的就是mutations了,mutattions也是一个对象,这个对象里面可以放改变state的初始值的方法,具体的用法就是给里面的方法传入参数state或额外的参数,然后利用vue的双向数据驱动进行值得改变,同样的定义好之后把这个mutations扔进Vuex.Store里面,如下:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state={//要设置的全局访问的state对象
showFooter:true,
changableNum:0
//要设置的初始属性值
};
const getters={//实时监听state值得变化(最新状态)
isShow(state){//承载变化的showFooter的值
return state.showFooter
},
getChangedNum(){
return state.changableNum
}
};
const mutations={
show(state){//自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象);
state.showFooter=true;
},
hide(state){//同上
state.showFooter=false;
},
newNum(state,sum){//同上,这里面的参数除了state之外还传了需要增加的值sum
state.changableNum+=sum;
}
};
const store=new Vuex.Store({
state,
getters,
mutations
});
export default store;
这个时候你完全可以用用this.$store.commit('show')或this.$store.commit('hide')以及this.$store.commit('newNum',6)在别的组件里面进行改变showfooter和changableNum的值了,但这不是理想的改变值得方式;因为在Vuex中,mutations里面的方法都是同步事务,意思就是说:比如这里的一个this.$store.commit('newNum',sum)方法,两个组件里用执行得到的值,每次都是一样的,这样肯定不是理想的需求
好在vuex官方API还提供了一个actions,这个actions也是个对象变量,最大的作用就是里面的Actions方法可以包含任意异步操作,这里面的方法是用力啊异步触发mutations里面的方法,actions里面自定义的函数接收一个context参数和要变化的形参,context与store实例具有相同的方法和属性,所以它可以执行context.commit(''),然后也不要忘了把它扔进Vuex.Store里面:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state={//要设置的全局访问的state对象
showFooter:true,
changableNum:0
//要设置的初始属性值
};
const getters={//实时监听state值得变化(最新状态)
isShow(state){//承载变化的showFooter的值
return state.showFooter
},
getChangedNum(){//承载幻化的changableNum的值
return state.changableNum
}
};
const mutations={
show(state){//自定义改变state初始值得方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象);
state.showFooter=true;
},
hide(state){//同上
state.showFooter=false;
},
newNum(state,sum){//同上,这里面的参数除了state之外还传了需要增加的值sum
state.changableNum+=sum;
}
};
const actions={
hideFooter(context){//自定义触发mutations里函数的方法,context与store实例具有相同方法和属性
context.commit('hide');
},
showFooter(context){//同上注释
context.commit('show')
},
getNewNum(context,num){//同上注释,num为要变化的形参
context.commit('newNum',num)
}
};
const store=new Vuex.Store({
state,
getters,
mutations,
actions
});
export default store;
而在外部组件里进行全局执行actions里面方法的时候,你只需要用执行
this.$store.dispatch('hideFooter')
或this.$store.dispatch('showFooter')
以及this.$store.dispatch('getNewNum',6)//6要变化的实参
这样就可以全局改变showFooter或changableNum的值了,如下面的组件中,需求是跳转组件页面后,根据当前所在的路由页面进行隐藏或显示页面底部的tabs选项卡
<template>
<div id="app">
<router-view/>
<FooterBar v-if="isShow" />
</div>
</template>
<script>
import FooterBar from '@/components/common/FooterBar'
import config from './config/index'
export default{
name:'App',
components:{
FooterBar:FooterBar
},
data(){
return{
}
},
computed:{
isShow(){
return this.$store.getters.isShow;
}
},
watch:{
$route(to,from){//跳转组件页面后,监听路由参数中对应的当前页面以及上一个页面
console.log(to);
if(to.name=='book'||to.name=='my'){//to.name来获取当前所显示的页面,从而控制该显示或隐藏footerVar组件
this.$store.dispatch('showFooter')//利用派发全局state.showFooter的值来控制
}else{
this.$store.dispatch('hideFooter')
}
}
}
}
</script>
至此就可以做到一呼百应的全局响应状态改变了!
modules模块化以及组件中引入mapGetters、mapActions和mapStates的使用
因为在大多数的项目中,我们对于全局状态的管理并不仅仅一种情况的需求,有时有多方面的需求,比如写一个商城项目,你所用到的全局state可能是关于购物车这一块的也有可能是关于商品价格这一块的,像这样的情况我们就要考虑使用vuex中的modules模块化了,具体怎么使用modules呢?我们继续一步一步的走:
首先,在store文件夹下面新建一个modules文件夹,然后再modules文件里面简历需要管理状态的js文件,既然要把不同部分的状态分开管理,那就把他们给分成独立的状态文件了,如下图:

而对应的store文件夹下面的index.js里面的内容就直接改写成:
import Vue from 'vue';
import Vuex from 'vuex';
import footerStatus from './modules/footerStatus'
import collection from './modules/collection'
Vue.use(Vuex); export default new Vuex.Store({
modules:{
footerStatus,
collection
}
})
相应的js,其中的namespaced:true 表示当你需要在别的文件里面使用(mapGetters、mapActions接下来会说)时,里面的方法需要注明来自哪一个模块的方法:
//collection.js
const state={
collects:[], //初始化一个colects数组
};
const getters={
renderCollects(state){ //承载变化的collects
return state.collects;
}
};
const mutations={
pushCollects(state,items){ //如何变化collects,插入items
state.collects.push(items)
}
};
const actions={
invokePushItems(context,item){ //触发mutations里面的pushCollects ,传入数据形参item 对应到items
context.commit('pushCollects',item);
}
};
export default {
namespaced:true,//用于在全局引用此文件里的方法时标识这一个的文件名
state,
getters,
mutations,
actions
}
//footerStatus.js
const state={ //要设置的全局访问的state对象
showFooter: true,
changableNum:0
//要设置的初始属性值
};
const getters = { //实时监听state值的变化(最新状态)
isShow(state) { //承载变化的showFooter的值
return state.showFooter
},
getChangedNum(){ //承载变化的changebleNum的值
return state.changableNum
}
};
const mutations = {
show(state) { //自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象);
state.showFooter = true;
},
hide(state) { //同上
state.showFooter = false;
},
newNum(state,sum){ //同上,这里面的参数除了state之外还传了需要增加的值sum
state.changableNum+=sum;
}
};
const actions = {
hideFooter(context) { //自定义触发mutations里函数的方法,context与store 实例具有相同方法和属性
context.commit('hide');
},
showFooter(context) { //同上注释
context.commit('show');
},
getNewNum(context,num){ //同上注释,num为要变化的形参
context.commit('newNum',num)
}
};
export default {
namespaced: true, //用于在全局引用此文里的方法时标识这一个的文件名
state,
getters,
mutations,
actions
}
这样一改就有了关于两个模块的state管理文件了 footerStatus.js和collection.js,现在你要运行当前的代码话,项目会报错!因为我们把上面的代码模块化分开了,引用的地方还没有改。接下来咱们一起来看看 mapState,mapGetters,mapActions的使用,首先 在需要用的 组件里面先导入 import {mapState,mapGetters,mapActions} from 'vuex';咱们先修正一下隐藏或显示页面底部的tabs选项卡(就是上面举的临时例子)的组件代码
<template>
<div id="app">
<router-view/>
<FooterBar v-if="isShow" />
</div>
</template> <script>
import {mapState,mapGetters,mapActions} from 'vuex'; //先要引入
import FooterBar from '@/components/common/FooterBar'
import config from './config/index'
export default {
name: 'App',
components:{
FooterBar:FooterBar
},
data(){
return {
}
},
computed:{
...mapState({ //这里的...是超引用,ES6的语法,意思是state里有多少属性值我可以在这里放多少属性值
isShow:state=>state.footerStatus.showFooter //注意这些与上面的区别就是state.footerStatus,
//里面定义的showFooter是指footerStatus.js里state的showFooter
}),
//你也可以用下面的mapGetters来获取isShow的值,貌似下面的更简洁
/*...mapGetters('footerStatus',{ //footerStatus指的是modules文件夹下的footerStatus.js模块
isShow:'isShow' //第一个isShow是我自定义的只要对应template里v-if="isShow"就行,
//第二个isShow是对应的footerStatus.js里的getters里的isShow
})*/
},
watch:{
$route(to,from){
if(to.name=='book'||to.name=='my'){
this.$store.dispatch('footerStatus/showFooter') //这里改为'footerStatus/showFooter',
//意思是指footerStatus.js里actions里的showFooter方法
}else{
this.$store.dispatch('footerStatus/hideFooter') //同上注释
}
}
}
}
</script>
现在项目代码应该就不会报错了,好,最后咱们再来看一下mapActions的用法,实际上上面的this.$store.dispatch('footerStatus/showFooter')已经算是一种执行相应模块的action里的方法了,但有时会牵扯的事件的触发及传值,那就会有下面的mapActions用法了,还记得上面的另一个模块collection.js吗?来看一下里面的actions中的方法结构:
const state={
collects:[], //初始化一个colects数组
};
const getters={
renderCollects(state){ //承载变化的collects
return state.collects;
}
};
const mutations={
pushCollects(state,items){ //如何变化collects,插入items
state.collects.push(items)
}
};
const actions={
invokePushItems(context,item){ //触发mutations里面的pushCollects ,传入数据形参item 对应到items
context.commit('pushCollects',item);
}
};
需要传值来实时变动state.collects里的数据,那肯定要在执行它的地方进行传值了,所以下面用到它的地方我们用了个@click来执行这个invokePushItems方法了,并且传入相应的对象数据item,如下:
<template>
<div >
<section class="joinState">
<div class="joinStateHead">
<span class="h3">全国改性料通讯录</span>
<span class="joinStatus" @click="invokePushItems(item)">加入收藏列</span>
</div>
</section>
</div>
</template> <script>
import { mapActions } from 'vuex'
export default {
components:{
conditionFilter
},
name: 'bookDetail',
data () {
return {
msg: '',
item:{
id:'01',
productName: '苹果',
price:'1.6元/斤'
}
}
},
mounted() {
this.$store.dispatch('footerStatus/hideFooter')
},
methods:{
...mapActions('collection',[ //collection是指modules文件夹下的collection.js
'invokePushItems' //collection.js文件中的actions里的方法,在上面的@click中执行并传入实参
])
} }
</script>
这样一来,在这个组件里面操作的 collecttion.js 中的state的数据,在其他的任何的一个组件里面都会得到相应的更新变化了,获取状态的页面代码如下:
<template>
</div>
<div>
<ul>
<li v-for="(val,index) in arrList" :key="index">
<h5>{{val.productName}}</h5>
<p>{{val.price}}</p>
</li>
</ul>
</div>
</template> <script>
import {mapState,mapGetters,mapActions} from 'vuex';
export default {
name: 'book',
data() {
return {
}
},
computed:{
// ...mapState({ //用mapState来获取collection.js里面的state的属性值
// arrList:state=>state.collection.collects
// }),
...mapGetters('collection',{ //用mapGetters来获取collection.js里面的getters
arrList:'renderCollects'
}) }
}
</script>
完结!
学习来源:https://segmentfault.com/a/1190000015782272
vuex学习及使用的更多相关文章
- vuex学习总结
vuex 学习 mapState,mapGetters 一般也写在 computed 中 , mapActions 一般写在 methods中.
- vuex学习详细解(主页目录
学习vuex过程中,通过 vue-cli命令来配置和使用vuex笔记整理 vue-cli中配置vuex流程和注意事项 vuex目录配置 vuex的states.js vuex的getters.js v ...
- Vuex 学习总结
好在之前接触过 flux,对于理解 vuex 还是很有帮助的.react 学到一半,后来因为太忙,就放弃了,现在也差不多都忘记了.不过感觉 vuex 还是跟 flux 还是有点区别的. 对于很多新手来 ...
- 【转】Vuex 学习总结
对于很多新手来说,只是阅读文档是不好消化,我的建议是看看 vuex 的实例,通过研究实例来学习vuex.这样就会好理解多了.如果还是不能理解,最好办法就是先把store 的四个属性:state, ge ...
- Vuex 学习笔记
Vuex 是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式.由于SPA应用的模块化,每个组件都有它各自的数据(state).视图(view)和方法(actions),当项目内容越 ...
- vuex学习笔记
一.vuex的目的 把组件的共享状态抽取出来,以一个全局单例模式管理.在这种模式下,组件树构成了一个巨大的视图,不管在树的哪个位置,任何组件都能获取状态或触发行为. 二.vuex集中式管理数据 安装 ...
- vuex学习(二)
参考:https://segmentfault.com/a/1190000015782272 vue 2.0+ 你的vue-cli项目中安装 vuex : npm install vuex --sav ...
- vuex学习
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. 简单的理解就是你在state中定义了一个数 ...
- vue之vuex学习
知识点一:vuex是状态管理器(单向数据流) 每个Vuex应用程序的核心是商店.“商店”基本上是一个容纳您的应用程序状态的容器.有两件事使Vuex商店与普通的全局对象不同: Vuex商店是被动的.当V ...
随机推荐
- spring web参数传递
spring boot 参数相关 ****************************************** @RequestParam 这个注解用来绑定单个请求数据,既可以是url中的 ...
- ABP框架系列之五:(Unit Of Work-工作单元)
Introduction Connection and transaction management is one of the most important concepts in an appli ...
- vue子传父多个值
子组件:this.$emit("methdosName",data1,data2,data3) 父组件: <child @methodsName="xxx(argu ...
- sshpass 使用方法
首先下载sshpass并且安装 $ tar -zxvf sshpass-1.06.tar.gz $ cd sshpass-1.06 $ ./configure --prefix=/usr/local/ ...
- elasticsearch搜索引擎环境的搭建
elasticsearch 搜索引擎 解决了什么问题:在我们数据量很大时,我们使用模糊查询会使索引列的索引消失,这样使用elasticsearch来提高查询效率. 存在什么问题:有时我们查询的词,el ...
- Golang 调用 Python 代码
go 中的 cgo 模块可以让 go 无缝调用 c 或者 c++ 的代码,而 python 本身就是个 c 库,自然也可以由 cgo 直接调用,前提是指定正确的编译条件,如 Python.h 头文件( ...
- SQL Server使用证书最小粒度授权
最近在项目中某个功能遇到了阻塞造成的Time out错误.所以需要在执行该功能的时候开启一个线程检测SQL Server中阻塞会话.但是程序本身使用的sql帐号本身不具备VIEW Sever Stat ...
- 关于调试WCF时引发的异常XmlException: Name cannot begin with the '<' character, hexadecimal value 0x3C” on Client Side
问题描述:在使用VS2015调试WCF时,偶遇抛出异常名称不能以“<”字符(十六进制0x3c)开头,平时运行时(不调试)没有问题的. 解决方法:检查后发现为了检查异常的位置,勾选了引发通用语言运 ...
- poj3280
将给定字符串用最小代价(添加,删除)变为回文串. dp:dp[i][j]表示将i-j变为回文串的最小代价. 若s[i]==s[j],则dp[i][j]=dp[i+1][j-1] 否则,若s[i+1]- ...
- 建立一个类似于天眼的Android应用程序:第4部分 - 持久收集联系人,通话记录和短信(SMS)
建立一个类似于天眼的Android应用程序:第4部分 - 持久收集联系人,通话记录和短信(SMS) 电话黑客android恶意软件编程黑客入侵linux 随着我们继续我们的系列,AMUNET应用程序变 ...