1.简介

  首先,你必须明显明白vuex到底是干啥的,主要解决开发中的哪些问题?

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

  说白了,就是:提供了那么一个公共存储的地方,存放各个组件的数据,组件访问数据和操作数据访问这个地方即可

  所以,Vuex主要解决是组件间数据传递问题,尤其是嵌套组件,项目一大时,父子组件间的数据传递就非常麻烦了,而Vuex则提供了一种集中管理组件数据的方案,当然小型项目就没必要用Vuex了

2.Demo准备

  • vue init webpack-simple vuex-demo
  • cd vuex-demo
  • npm install
  • npm install vuex -S

3.访问store对象的两种方式  

  Vuex的核心是Store(仓库),相当于是一个容器,一个store实例中包含以下属性的方法:

  • state  定义属性(状态、数据)
  • getters  用来获取属性
  • actions  定义方法(动作)
  • commit  提交变化,修改数据的唯一方式就是显式的提交mutations
  • mutations  定义变化

  注:不能直接修改数据,必须显式提交变化,目的是为了追踪到状态的变化

  创建store.js文件,在main.js中导入并配置store.选项

import Vue from 'vue'
import Vuex from 'vuex' Vue.use(Vuex); //定义属性(数据)
var state = {
count: 6
} //创建store对象
const store = new Vuex.Store({
state,
}) //导出store对象
export default store;
import Vue from 'vue'
import App from './App.vue' import store from './store.js' //导入store对象 new Vue({
store,
el: '#app',
render: h => h(App)
})

 

  方式一:通过this.$store访问

  //方式1:通过this.$store访问
computed: {
count() {
return this.$store.state.count;
}
}

  方式二:通过mapState、mapGetters、mapActions访问,vuex提供了两个方法

  • mapState  获取state
  • mapGetters  获取getters
  • mapActions  获取actions
import Vue from 'vue'
import Vuex from 'vuex' Vue.use(Vuex); //定义属性(数据)
var state = {
count: 6
} //定义getters
var getters = {
count(state) {
return state.count;
}
} //定义actions,要执行的操作,如流程判断、异步请求
const actions = {
increment(context) { //包含 commit dispatch state
context.commit('increment');
},
decrement(context) {
if (context.state.count > 10) {
context.commit('decrement');
}
}
} //定义mutations,处理状态(数据)的改变
const mutations = {
increment(state) {
state.count++;
},
decrement(state) {
state.count--;
}
} //创建store对象
const store = new Vuex.Store({
state,
getters,
actions,
mutations,
}) //导出store对象
export default store;
<template>
<div id="app">
<button @click="increment">增加</button>
<button @click="decrement">减小</button>
<p>当前数字为:{{count}}</p>
</div>
</template> <script>
import { mapState, mapGetters, mapActions } from "vuex"; export default {
name: "app",
data() {
return {
msg: "Welcome to Your Vue.js App"
};
},
//方式1:通过this.$store访问
/*computed: {
count() {
return this.$store.state.count;
}
}*/ /*computed:mapState([
'count'
])*/ computed: mapGetters(["count"]),
methods:mapActions([
'increment',
'decrement',
])
};
</script> <style>
</style>

  

分模块组织Vuex

  上面那种方式,所有的都写在一个文件,项目大时,难免看起来显乱,所以需要分模块来组织,原则上就私有和公共的分开进行组织

  其中modules存放每个模块的,actions.js,getters.js,mutations.js存放公共的,目录如下

user.js

/**
* 用户模块
*/ import types from '../types.js' const state={
count:6
} var getters={
count(state){
return state.count;
}
} const actions = {
increment({commit,state}){
commit(types.INCREMENT); //提交一个名为increment的变化,名称可自定义,可以认为是类型名
},
decrement({commit,state}){
if(state.count>10){
commit(types.DECREMENT);
}
}
} const mutations={
[types.INCREMENT](state){
state.count++;
},
[types.DECREMENT](state){
state.count--;
}
} export default {
state,
getters,
actions,
mutations
}

  

actions.js

import types from './types.js'

const actions={
incrementAsync({commit,state}){
//异步操作
var p=new Promise((resolve,reject) => {
setTimeout(() => {
resolve();
},3000);
}); p.then(() => {
commit(types.INCREMENT);
}).catch(() => {
console.log('异步操作');
});
}
} export default actions;

  

getters.js

const getters={
isEvenOrOdd(state){
return state.user.count%2==0?'偶数':'奇数';
}
} export default getters;

  

types.js

/**
* 定义类型常量
*/ const INCREMENT='INCREMENT'
const DECREMENT='DECREMENT' export default {
INCREMENT,
DECREMENT
}

  

index.js

import Vue from 'vue'
import Vuex from 'vuex' Vue.use(Vuex); import getters from './getters.js'
import actions from './actions.js'
import user from './modules/user.js' export default new Vuex.Store({
getters,
actions,
modules:{
user
}
});

  

main.js

import Vue from 'vue'
import App from './App.vue' import store from './store/index.js' new Vue({
store,
el: '#app',
render: h => h(App)
})

分模块组织的访问

        console.log(this.$store);
console.log(this.$store.getters['dirTestcaseData']);
console.log(this.$store.getters['user/count']); console.log(this.$store.state['project']);
console.log(this.$store.state.user['count']); this.$store.dispatch("asset/changeCurrentFundIndex", index);
this.$store.dispatch('increment'); //导入
import { mapState, mapGetters } from "vuex"; //批量引入
...mapGetters("asset", {
assetDetailType: "assetDetailType",
tradeSelectVal: "tradeSelectVal",
totalAsset: "totalAsset"
}) //也支持数组

一篇搞定Vuex的更多相关文章

  1. 一篇搞定RSA加密与SHA签名|与Java完全同步

    基础知识 什么是RSA?答:RSA是一种非对称加密算法,常用来对传输数据进行加密,配合上数字摘要算法,也可以进行文字签名. RSA加密中padding?答:padding即填充方式,由于RSA加密算法 ...

  2. 2021升级版微服务教程6—Ribbon使用+原理+整合Nacos权重+实战优化 一篇搞定

    2021升级版SpringCloud教程从入门到实战精通「H版&alibaba&链路追踪&日志&事务&锁」 教程全目录「含视频」:https://gitee.c ...

  3. 一篇搞定微信分享和line分享

    前言 在h5的页面开发中,分享是不可或缺的一部分,对于一些传播性比较强的页面,活动页之类的,分享功能极为重要.例如,京东等电商年末时会有一系列的总结h5在微信中传播,就不得不提到微信的分享机制. 微信 ...

  4. 一篇搞定MongoDB

    MongoDB最基础的东西,我这边就不多说了,这提供罗兄三篇给大家热身 MongoDB初始 MongoDB逻辑与物理存储结构 MongoDB的基础操作 最后对上述内容和关系型数据做个对比 非关系型数据 ...

  5. 【java 数据结构】还不会二叉树?一篇搞定二叉树

    二叉树是我们常见的数据结构之一,在学习二叉树之前我们需要知道什么是树,什么是二叉树,本篇主要讲述了二叉树,以及二叉树的遍历. 你能get到的知识点? 1.树的介绍 2.二叉树的介绍 3.二叉树遍历的四 ...

  6. 一篇搞定Python正则表达式

    1. 正则表达式语法 1.1 字符与字符类 1 特殊字符:\.^$?+*{}[]()| 以上特殊字符要想使用字面值,必须使用\进行转义 2 字符类    1. 包含在[]中的一个或者多个字符被称为字符 ...

  7. python 一篇搞定所有的异常处理

    一:什么是异常? 异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行. 一般情况下,在python无法正常处理程序时就会发生一个异常(异常是python对象,表示一个错误) 异常就是 ...

  8. 阿里巴巴(alibaba)系列_druid 数据库连接池_监控(一篇搞定)记录执行慢的sql语句

    参考帖子:http://www.cnblogs.com/han-1034683568/p/6730869.html Druid数据连接池简介 Druid是Java语言中最好的数据库连接池.Druid能 ...

  9. 一篇搞定vue请求和跨域

    vue本身不支持发送AJAX请求,需要使用vue-resource.axios等插件实现 axios是一个基本Promise的HTTP请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对v ...

随机推荐

  1. mybatis-config.xml文件详解

    1. 属性列表 Mybatis的配置文件中包含了影响mybatis行为的设置(settings)和属性(properties)信息.文档的顶层结构如下: ·configuration 根配置 ·pro ...

  2. Atitit.index manager api design 索引管理api设计

    Atitit.index manager api design 索引管理api设计 1. kw 1 1.1. 索引类型 unique,normal,fulltxt 1 1.2. 聚集索引(cluste ...

  3. C++语言基础(24)-四种类型转换运算符(static_cast、dynamic_cast、const_cast和reinterpret_cast)

    一.static_cast static_cast 只能用于良性转换,这样的转换风险较低,一般不会发生什么意外,如: #include <iostream> #include <cs ...

  4. LINQ----1

    Student[] stAry ={ ), ), ), ), ), ), }; var query1 = from vall in stAry select vall; foreach (Studen ...

  5. Android CoordinatorLayout 入门介绍

    Android CoordinatorLayout 入门介绍 CoordinatorLayout View 知道如何表现 在 2015 年的 I/O 开发者大会上,Google 介绍了一个新的 And ...

  6. Echarts中线状图的X轴坐标标签倾斜样式

    在echarts中应用线状图时可以展现很多的数据,而当数据量过多的时候,X轴的坐标就会显示不全,因为整个图形的宽度是一定的,X轴的全长是一定的 http://www.cnblogs.com/phpgc ...

  7. Guardian of Decency UVALive - 3415 最大独立集=结点数-最大匹配数 老师带大学生旅游

    /** 题目:Guardian of Decency UVALive - 3415 最大独立集=结点数-最大匹配数 老师带大学生旅游 链接:https://vjudge.net/problem/UVA ...

  8. 线程同步工具CountDownLatch

    CountDownLatch的一个非常典型的应用场景是:有一个任务想要往下执行,但必须要等到其他的任务执行完毕后才可以继续往下执行.假如我们这个想要继续往下执行的任务调用一个CountDownLatc ...

  9. 请用正则表达式匹配出QQ号(假设QQ号码为5—10位);

    请用正则表达式匹配出QQ号(假设QQ号码为5—10位): 解答: ^ \d{5,10}$

  10. 【BZOJ】3403: [Usaco2009 Open]Cow Line 直线上的牛(模拟)

    http://www.lydsy.com/JudgeOnline/problem.php?id=3404 裸的双端队列.. #include <cstdio> #include <c ...