1.Vuex是什么

  Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,用于管理页面的数据状态、提供统一数据操作的生态系统。在组件中可以任意获取仓库中的数据。和Vuex类似的还有redux,redux一般在react中使用比较多。

   ----来自官方示例图

  1.在组件中,通过dispatch一个Actions->Mutations->State,最后渲染组件

  2.其中在actions可以异步操作。不需要异步操作时,只需要commit一个mutions去修改仓库中的数据,然后组件就会渲染。

  3.并且vuex是响应式的,如果仓库(state)中的数据被更改了,那么页面也会相应的更新

  4.其中vuex规定了。仓库(state)中的数据更改必须通过mutations。不可以直接修改。

2.安装

  1.通过src方式引入静态文件

     <script src="/path/to/vue.js"></script>

     <script src="/path/to/vuex.js"></script>

  2.通过npm/yarn安装

     npm install vuex -S

     yarn add vuex

3.注入vuex

  在cli中新建index.js,通过import vuex from 'vuex'引入

import Vue from 'vue';
import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {}
});
main.js

import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store'; Vue.config.productionTip = false; new Vue({
router,
store,
render: h => h(App)
}).$mount('#app');

3.核心概念

  State:

    1.说明:

      仓库中的数据都保存在这。并且全局只有一个唯一实例,以对象形式存在

    2.基本使用:

      // index.js

import Vue from 'vue';
import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({
state: {
count: 1
},
mutations: {},
actions: {},
modules: {}
});

    组件中: 

<template>
<div>
<p>state中的count:{{ $store.state.count }}</p>
</div>
</template> <script>
export default {
created() {
console.log(this.$store.state.count);
}
};
</script> <style scoped lang="scss">
* {
margin: 0;
font-size: 20px;
}
</style>

    通过this.$store.state获取仓库所有数据

    3.辅助函数

      mapState:返回的是一个对象

        1.引入:在组件中import { mapState } from 'vuex'

        2.使用:mapState和computed    

<template>
<div>
<p>state中的count:{{ count }}</p>
<p>{{ sum }}</p>
</div>
</template> <script>
import { mapState } from 'vuex';
export default {
data() {
return {
a: 1,
b: 2
};
},
created() {
// console.log(this.$store.state.count);
},
computed: mapState({
// 返回state中的count
count: state => state.count, // 其它计算属性
sum() {
return this.a + this.b;
}
})
};
</script>

        3.使用扩展运算符...简化

    computed: {
// 使用字符串数组写法
...mapState(['count']),
// 其它计算属性
sum() {
return this.a + this.count;
}
}
    computed: {
// 使用对象写法
...mapState({
countAlias: 'count'
}),
// 其它计算属性
sum() {
return this.a + this.countAlias;
}
}

  Getters:

    1.说明:

      getters就是将state中的数据包装一个在返回,接受第一个参数state,可以访问state中的数据。也可以接受第二个参数其它的getter

    2.基本使用

import Vue from 'vue';
import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({
state: {
list: [1, 2, 3, 4, 5, 6]
},
getters: {
filterList: state => {
return state.list.filter(i => i > 3);
}
},
mutations: {},
actions: {},
modules: {}
});
import Vue from 'vue';
import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({
state: {
count: 1,
list: [1, 2, 3, 4, 5, 6]
},
getters: {
// 使用其他getters
initData: (state, getters) => {
return getters.filterList.map(i => i + state.count);
},
filterList: state => {
return state.list.filter(i => i > 3);
}
},
mutations: {},
actions: {},
modules: {}
});

    组件中:

<template>
<div>
<p>getter中的sum返回值:{{ $store.getters.filterList }}</p>
<p>使用其他getter:{{ $store.getters.initData }}</p>
</div>
</template> <script>
export default {
data() {
return {
a: 1
};
},
created() {
console.log(this.$store.getters.filterList);
},
computed: {}
};
</script>

    通过this.$store.getter获取所有getters

    3.在getter中返回一个函数,实现使用getter时传参

getters: {
filterList: state => data => {
return state.list.find(i => i === data);
}
}, <template>
<div>
<p>getter中的sum返回值:{{ $store.getters.filterList(2) }}</p>
</div>
</template>

    3.辅助函数:

      mapGetters

        1.引入:import { mapGetters } from 'vuex';

        2.使用:mapGetters和computed

          传递字符串数组

<template>
<div>
<p>getter中的sum返回值:{{ filterList(2) }}</p>
</div>
</template> <script>
import { mapGetters } from 'vuex';
export default {
data() {
return {
a: 1
};
},
created() {
console.log(this.$store.getters.filterList);
},
computed: {
...mapGetters(['filterList'])
}
};
</script>

          使用对象形式

<template>
<div>
<p>getter中的sum返回值:{{ filterListAlias(2) }}</p>
</div>
</template> <script>
import { mapGetters } from 'vuex';
export default {
data() {
return {
a: 1
};
},
created() {
console.log(this.$store.getters.filterList);
},
computed: {
...mapGetters({
filterListAlias: 'filterList'
})
}
};
</script>

  Mutation

    1.说明:

      mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数

      在mutation中不可以做异步操作

    2.基本使用

import Vue from 'vue';
import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({
state: {
count: 1
},
getters: {},
mutations: {
increment(state) {
state.count++;
}
},
actions: {},
modules: {}
});

      组件中:

<template>
<div>
<p>state中的count:{{ $store.state.count }}</p>
<button @click="clickFn">+</button>
</div>
</template> <script>
export default {
data() {
return {
a: 1
};
},
created() {},
methods: {
clickFn() {
this.$store.commit('increment');
}
}
};
</script>

    通过this.$store.commit('increment');方式修改state中的数据。注意这里的increment解释为mutation的事件类型,并不是函数名称

    a.传参使用,接受第二个参数payload

定义:
mutations: {
increment(state, payload) {
state.count += payload;
}
}, 组件使用:
methods: {
clickFn() {
this.$store.commit('increment', '我是参数');
}
}

    b.提交方式,一般使用对象形式提交

    methods: {
clickFn() {
this.$store.commit({
type: 'increment',
data: '我是参数1',
data2: '我是参数2'
});
}
} mutations: {
increment(state, payload) {
state.count = state.count + payload.data + payload.data2;
}
},

    c.使用常量代替mutation类型事件

       1.新建mutation-types.js文件

          export const SOME_MUTATION = 'someMutation';

       2.引入定义的类型,并使用     

import Vue from 'vue';
import Vuex from 'vuex';
import { SOME_MUTATION } from './mutationTypes'; Vue.use(Vuex); export default new Vuex.Store({
state: {
count: 1
},
getters: {},
mutations: {
[SOME_MUTATION](state, payload) {
state.count += payload.data;
}
},
actions: {},
modules: {}
});

       3.在组件中使用

<template>
<div>
<p>state中的count:{{ $store.state.count }}</p>
<button @click="clickFn">+</button>
</div>
</template> <script>
import { SOME_MUTATION } from '../../store/mutationTypes';
export default {
data() {
return {
a: 1
};
},
created() {},
methods: {
clickFn() {
this.$store.commit(SOME_MUTATION, {
data: 1
});
}
}
};
</script>

    3.辅助函数

      mapMutations

        1.引入:import { mapMutations } from 'vuex';

        2.使用:mapMutations和methods

           使用类型时,使用对象形式,将SOME_MUTATION映射为add

    mutations: {
[SOME_MUTATION](state, payload) {
state.count += payload.data;
}
}, methods: {
...mapMutations({
add: SOME_MUTATION
}),
clickFn() {
this.add({ data: 2 });
}
}

          不使用类型时

    mutations: {
add(state, payload) {
state.count += payload.data;
}
}, methods: {
...mapMutations(['add']),
clickFn() {
this.add({ data: 2 });
}
}

  Action

    1.说明:

      action类似于mutation,但是action提交的是mutation,而不是直接修改state,也就是通过action提交mutation,然后commit修改state,action可以异步操作

      Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,通过context 访问context.state,context.commit,context.getters,context.dispatch等。

      通过dispatch方法触发

    2.基本使用

export default new Vuex.Store({
state: {
count: 1
},
getters: {},
mutations: {
add(state) {
state.count += 1;
}
},
actions: {
increment(context) {
context.commit('add');
}
},
modules: {}
});

    组件中  

<template>
<div>
<p>state中的count:{{ $store.state.count }}</p>
<button @click="add">+</button>
</div>
</template> <script>
export default {
data() {
return {
a: 1
};
},
created() {},
methods: {
add() {
this.$store.dispatch('increment');
}
}
};
</script>

    通常会使用解构来简化代码

    actions: {
increment({ commit, state, getters }) {
commit('add');
}
},

    传递参数

    methods: {
add() {
this.$store.dispatch('increment', {
data: 21
});
this.$store.dispatch({
type: 'increment',
data: 21
});
}
} export default new Vuex.Store({
state: {
count: 1
},
getters: {},
mutations: {
add(state, payload) {
state.count += payload.data;
}
},
actions: {
increment({ commit, state, getters }, payload) {
commit('add', payload);
}
},
modules: {}
});

    辅助函数

      mapActions

        1.引入:import { mapActions } from 'vuex';

        2.使用:mapActions和methods

    methods: {
// ...mapActions(['increment']),
...mapActions({
incrementAlias: 'increment'
}),
add() {
this.incrementAlias({ data: 1 });
}
}

  Module

    略

      

            

Vuex理解与使用的更多相关文章

  1. vuex理解之modules小记

    好记性不如烂笔头 demo预览 源代码 前情提要 关于vuex,其实很久以前就研究使用过,还研究过 flux,redux之类的体系,当时感觉对于 state,action,dispatch,views ...

  2. vuex 理解

    为什么要用vuex?页面由多个视图组成,用户操作会引视图的状态变化. 多个视图依赖于同一状态(例如:菜单导航) 来自不同视图的行为需要变更同一状态(例如:评论弹幕) vuex 的作用 为vue.js开 ...

  3. VueX理解

    什么是Vuex? 官方说法:Vuex 是一个专为 Vue.js应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. 个人理解:Vue ...

  4. vuex所有核心概念完整解析State Getters Mutations Actions

    vuex是解决vue组件和组件件相互通信而存在的,vue理解起来稍微复杂但一旦看懂择即为好用 安装: npm install --save vuex 引入 import Vuex from 'vuex ...

  5. vue2.x中请求之前数据显示以及vuex缓存的问题

    在项目中遇到两个问题,简单的做个笔记来记录自己解决的问题,可能不是很好的处理办法,欢迎提出,自己还在不断优化中... 第一个是vue在加载页面的时候,会先加载静态资源,这个时候数据还没有请求回来,用户 ...

  6. 前端Vue框架-vuex状态管理详解

    新人报道!多多关照-多提宝贵意见 谢谢- vuex理解 采用集中式存储管理模式.用来管理组件的状态,并以自定义规则去观测实时监听值得变化. 状态模式管理理解 属性 理解 state 驱动应用的数据源 ...

  7. MVC和MVVM设计模式简单理解

    1.mvc设计模式理解 Model: 模型 持有所有的数据状态和业务逻辑; 泛指数据库,链接数据库,建立数据模型 View: 视图 用来展示数据模型在页面上,泛指前端 Controller: 控制器, ...

  8. 干货分享:vue2.0做移动端开发用到的相关插件和经验总结(2)

    最近一直在做移动端微信公众号项目的开发,也是我首次用vue来开发移动端项目,前期积累的移动端开发经验较少.经过这个项目的锻炼,加深了对vue相关知识点的理解和运用,同时,在项目中所涉及到的微信api( ...

  9. Vue 全家桶

    第 1 章:Vue 核心 1.1. Vue 的基本认识1.1.1. 官网1) 英文官网: https://vuejs.org/2) 中文官网: https://cn.vuejs.org/ 1.1.2. ...

随机推荐

  1. HDOJ 2955

    这道背包题和我们常见的背包题有所不同.如果根据以前做背包的惯性思维和题中数据的迷惑,会把概率乘以100来当作容量.但是经测试是不行的. 我们不妨换种思路,看做DAG上的DP思想.将所有有可能达到的钱的 ...

  2. Educational Codeforces Round 87 (Rated for Div. 2) D树状数组加二分删除的值

    Sample Input 5 4 1 2 3 4 5 -5 -1 -3 -1 Sample Output 3 思路,首先发现a[i]的值的范围是在1~n之间,每次插入我们可以直接把cnt[a[i]]+ ...

  3. hdu 6863 Isomorphic Strings 哈希+求公因子

    题意: t组输入,每组数据输入一个整数n,代表字符串长度.下面再输入一个字符串 你需要判断这个字符串能不能分成大于1段,且这些段的最小表示法是一样的 例如:abccab,它可以分成2段,分别是abc和 ...

  4. Codeforces Round #550 (Div. 3) D. Equalize Them All (贪心,模拟)

    题意:有一组数,可以选择某个数\(a_i\)相邻的一个数\(a_j\),然后可以让\(a_i\)加上或者减去\(|a_i-a_j|\),问最少操作多少次使得数组中所有数相同. 题解:不难发现,每次操作 ...

  5. Codeforces Round #577 (Div. 2) C. Maximum Median (模拟,中位数)

    题意:给你一个长度为奇数\(n\)的序列.你可以对任意元素加上\(k\)次\(1\),求操作后的中位数最大. 题解:先对序列进行排序,然后对中位数相加,如果中位数和后面的元素相等,就对后面所有和当前中 ...

  6. POJ - 1654 利用叉积求三角形面积 去 间接求多边形面积

    题意:在一个平面直角坐标系,一个点总是从原点出发,但是每次移动只能移动8个方向的中的一个并且每次移动距离只有1和√2这两种情况,最后一定会回到原点(以字母5结束),请你计算这个点所画出图形的面积 题解 ...

  7. Codeforces Round #658 (Div. 2) C1. Prefix Flip (Easy Version) (构造)

    题意:给你两个长度为\(n\)的01串\(s\)和\(t\),可以选择\(s\)的前几位,取反然后反转,保证\(s\)总能通过不超过\(3n\)的操作得到\(t\),输出变换总数,和每次变换的位置. ...

  8. Web 安全漏洞 All In One

    Web 安全漏洞 All In One Web 安全 & 漏洞 输入输出验证不充分 SQL 注入 XSS self-XSS CSRF 目录穿越 文件上传 代码注入 命令注入 信息漏洞 暴力破解 ...

  9. Docker In Action

    Docker In Action Docker 实战 https://docs.docker.com/get-started/overview/ Docker Engine Docker Archit ...

  10. historyReverser & array reverse

    historyReverser & array reverse\ "use strict"; /** * * @author xgqfrms * @license MIT ...