Vuex简介
一. 什么是Vuex?

Vuex是一个专门为Vue.js应用程序开发的状态管理模式, 它采用集中式存储管理所有组件的公共状态, 并以相应的规则保证状态以一种可预测的方式发生变化.
上图中绿色虚线包裹起来的部分就是Vuex的核心, state中保存的就是公共状态, 改变state的唯一方式就是通过mutations进行更改. 可能你现在看这张图有点不明白, 等经过本文的解释和案例演示, 再回来看这张图, 相信你会有更好的理解.
二. 为什么要使用Vuex?
试想这样的场景, 比如一个Vue的根实例下面有一个根组件名为App.vue, 它下面有两个子组件A.vue和B.vue, App.vue想要与A.vue或者B.vue通讯可以通过props传值的方式, 但是如果A.vue和B.vue之间的通讯就很麻烦了, 他们需要共有的父组件通过自定义事件进行实现, A组件想要和B组件通讯往往是这样的:
- A组件说: "报告老大, 能否帮我托个信给小弟B" => dispatch一个事件给App
- App老大说: "包在我身上, 它需要监听A组件的dispatch的时间, 同时需要broadcast一个事件给B组件"
- B小弟说: "信息已收到", 它需要on监听App组件分发的事件
这只是一条通讯路径, 如果父组件下有多个子组件, 子组件之间通讯的路径就会变的很繁琐, 父组件需要监听大量的事件, 还需要负责分发给不同的子组件, 很显然这并不是我们想要的组件化的开发体验.
Vuex就是为了解决这一问题出现的
三.如何引入Vuex?
- 下载
vuex:npm install vuex --save - 在
main.js添加:
import Vuex from 'vuex'
Vue.use( Vuex );
const store = new Vuex.Store({
//待添加
})
new Vue({
el: '#app',
store,
render: h => h(App)
})
四. Vuex的核心概念?
在介绍Vuex的核心概念之前, 我使用vue-cli初始化了一个demo, 准备以代码的形式来说明Vuex的核心概念, 大家可以在github上的master分支进行下载.这个demo分别有两个组件ProductListOne.vue和ProductListTwo.vue, 在App.vue的datat中保存着共有的商品列表, 代码和初始化的效果如下图所示:
//App.vue中的初始化代码
<template>
<div id="app">
<product-list-one v-bind:products="products"></product-list-one>
<product-list-two v-bind:products="products"></product-list-two>
</div>
</template>
<script>
import ProductListOne from './components/ProductListOne.vue'
import ProductListTwo from './components/ProductListTwo.vue'
export default {
name: 'app',
components: {
'product-list-one': ProductListOne,
'product-list-two': ProductListTwo
},
data () {
return {
products: [
{name: '鼠标', price: 20},
{name: '键盘', price: 40},
{name: '耳机', price: 60},
{name: '显示屏', price: 80}
]
}
}
}
</script>
<style>
body{
font-family: Ubuntu;
color: #555;
}
</style>
//ProductListOne.vue
<template>
<div id="product-list-one">
<h2>Product List One</h2>
<ul>
<li v-for="product in products">
<span class="name">{{ product.name }}</span>
<span class="price">${{ product.price }}</span>
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['products'],
data () {
return {
}
}
}
</script>
<style scoped>
#product-list-one{
background: #FFF8B1;
box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
margin-bottom: 30px;
padding: 10px 20px;
}
#product-list-one ul{
padding: 0;
}
#product-list-one li{
display: inline-block;
margin-right: 10px;
margin-top: 10px;
padding: 20px;
background: rgba(255,255,255,0.7);
}
.price{
font-weight: bold;
color: #E8800C;
}
</style>
//ProductListTwo.vue
<template>
<div id="product-list-two">
<h2>Product List Two</h2>
<ul>
<li v-for="product in products">
<span class="name">{{ product.name }}</span>
<span class="price">${{ product.price }}</span>
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['products'],
data () {
return {
}
}
}
</script>
<style scoped>
#product-list-two{
background: #D1E4FF;
box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
margin-bottom: 30px;
padding: 10px 20px;
}
#product-list-two ul{
padding: 0;
list-style-type: none;
}
#product-list-two li{
margin-right: 10px;
margin-top: 10px;
padding: 20px;
background: rgba(255,255,255,0.7);
}
.price{
font-weight: bold;
color: #860CE8;
display: block;
}
</style>
核心概念1: State
state就是Vuex中的公共的状态, 我是将state看作是所有组件的data, 用于保存所有组件的公共数据.
- 此时我们就可以把
App.vue中的两个组件共同使用的data抽离出来, 放到state中,代码如下:
//main.js
import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
Vue.use( Vuex )
const store = new Vuex.Store({
state:{
products: [
{name: '鼠标', price: 20},
{name: '键盘', price: 40},
{name: '耳机', price: 60},
{name: '显示屏', price: 80}
]
}
})
new Vue({
el: '#app',
store,
render: h => h(App)
})
- 此时,
ProductListOne.vue和ProductListTwo.vue也需要做相应的更改
//ProductListOne.vue
export default {
data () {
return {
products : this.$store.state.products //获取store中state的数据
}
}
}
//ProductListTwo.vue
export default {
data () {
return {
products: this.$store.state.products //获取store中state的数据
}
}
}
此时的页面如下图所示, 可以看到, 将公共数据抽离出来后, 页面没有发生变化.
state效果
到此处的Github仓库中代码为: 分支code01
核心概念2: Getters
我将getters属性理解为所有组件的computed属性, 也就是计算属性. vuex的官方文档也是说到可以将getter理解为store的计算属性, getters的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
- 此时,我们可以在
main.js中添加一个getters属性, 其中的saleProducts对象将state中的价格减少一半(除以2)
//main.js
const store = new Vuex.Store({
state:{
products: [
{name: '鼠标', price: 20},
{name: '键盘', price: 40},
{name: '耳机', price: 60},
{name: '显示屏', price: 80}
]
},
getters:{ //添加getters
saleProducts: (state) => {
let saleProducts = state.products.map( product => {
return {
name: product.name,
price: product.price / 2
}
})
return saleProducts;
}
}
})
- 将
productListOne.vue中的products的值更换为this.$store.getters.saleProducts
export default {
data () {
return {
products : this.$store.getters.saleProducts
}
}
}
- 现在的页面中,Product List One中的每项商品的价格都减少了一半
到此处的Github仓库中代码为: 分支code02
核心概念3: Mutations
我将mutaions理解为store中的methods, mutations对象中保存着更改数据的回调函数,该函数名官方规定叫type, 第一个参数是state, 第二参数是payload, 也就是自定义的参数.
- 下面,我们在
main.js中添加mutations属性,其中minusPrice这个回调函数用于将商品的价格减少payload这么多, 代码如下:
//main.js
const store = new Vuex.Store({
state:{
products: [
{name: '鼠标', price: 20},
{name: '键盘', price: 40},
{name: '耳机', price: 60},
{name: '显示屏', price: 80}
]
},
getters:{
saleProducts: (state) => {
let saleProducts = state.products.map( product => {
return {
name: product.name,
price: product.price / 2
}
})
return saleProducts;
}
},
mutations:{ //添加mutations
minusPrice (state, payload ) {
let newPrice = state.products.forEach( product => {
product.price -= payload
})
}
}
})
- 在
ProductListTwo.vue中添加一个按钮,为其添加一个点击事件, 给点击事件触发minusPrice方法
//ProductListTwo.vue
<template>
<div id="product-list-two">
<h2>Product List Two</h2>
<ul>
<li v-for="product in products">
<span class="name">{{ product.name }}</span>
<span class="price">${{ product.price }}</span>
</li>
<button @click="minusPrice">减少价格</button> //添加按钮
</ul>
</div>
</template>
- 在
ProductListTwo.vue中注册minusPrice方法, 在该方法中commitmutations中的minusPrice这个回调函数
注意:调用mutaions中回调函数, 只能使用store.commit(type, payload)
//ProductListTwo.vue
export default {
data () {
return {
products: this.$store.state.products
}
},
methods: {
minusPrice() {
this.$store.commit('minusPrice', 2); //提交`minusPrice,payload为2
}
}
}
- 添加按钮, 可以发现, Product List Two中的价格减少了2, 当然你可以自定义
payload,以此自定义减少对应的价格.
mutations效果
(Product List One中的价格没有发生变化,原因是getter 监听的是map方法产生的新对象)
到此处的Github仓库中代码为: 分支code03
核心概念4: Actions
actions 类似于 mutations,不同在于:
actions提交的是mutations而不是直接变更状态actions中可以包含异步操作,mutations中绝对不允许出现异步actions中的回调函数的第一个参数是context, 是一个与store实例具有相同属性和方法的对象此时,我们在
store中添加actions属性, 其中minusPriceAsync采用setTimeout来模拟异步操作,延迟2s执行 该方法用于异步改变我们刚才在mutaions中定义的minusPrice
//main.js
const store = new Vuex.Store({
state:{
products: [
{name: '鼠标', price: 20},
{name: '键盘', price: 40},
{name: '耳机', price: 60},
{name: '显示屏', price: 80}
]
},
getters:{
saleProducts: (state) => {
let saleProducts = state.products.map( product => {
return {
name: product.name,
price: product.price / 2
}
})
return saleProducts;
}
},
mutations:{
minusPrice (state, payload ) {
let newPrice = state.products.forEach( product => {
product.price -= payload
})
}
},
actions:{ //添加actions
minusPriceAsync( context, payload ) {
setTimeout( () => {
context.commit( 'minusPrice', payload ); //context提交
}, 2000)
}
}
})
- 在
ProductListTwo.vue中添加一个按钮,为其添加一个点击事件, 给点击事件触发minusPriceAsync方法
<template>
<div id="product-list-two">
<h2>Product List Two</h2>
<ul>
<li v-for="product in products">
<span class="name">{{ product.name }}</span>
<span class="price">${{ product.price }}</span>
</li>
<button @click="minusPrice">减少价格</button>
<button @click="minusPriceAsync">异步减少价格</button> //添加按钮
</ul>
</div>
</template>
- 在
ProductListTwo.vue中注册minusPriceAsync方法, 在该方法中dispatchactions中的minusPriceAsync这个回调函数
export default {
data () {
return {
products: this.$store.state.products
}
},
methods: {
minusPrice() {
this.$store.commit('minusPrice', 2);
},
minusPriceAsync() {
this.$store.dispatch('minusPriceAsync', 5); //分发actions中的minusPriceAsync这个异步函数
}
}
}
添加按钮, 可以发现, Product List Two中的价格延迟2s后减少了5
actions效果
到此处的Github仓库中代码为: 分支code04
核心概念5: Modules
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
【相关链接】
- 本文代码地址: https://github.com/Lee-Tanghui/Vuex-Demo
- Vuex官方文档: https://vuex.vuejs.org/zh-cn/intro.html
- Vuex官方案例演示源码: https://github.com/vuejs/vuex/tree/dev/examples
.
Vuex简介的更多相关文章
- 手摸手教你在vue-cli里面使用vuex,以及vuex简介
写在前面: 这篇文章是在vue-cli里面使用vuex的一个极简demo,附带一些vuex的简单介绍.有需要的朋友可以做一下参考,喜欢的可以点波赞,或者关注一下,希望可以帮到大家. 本文首发于我的个人 ...
- vuex简介(转载)
安装.使用 vuex 首先我们在 vue.js 2.0 开发环境中安装 vuex : npm install vuex --save 然后 , 在 main.js 中加入 : import vuex ...
- vuex使用报错
1.vuex简介 最近在玩vuex,不得不说它是一个很强大的工具,它的目的就是把数据统一管理起来,方便各个组件之间来回调用 2.vuex引用报错 当我们去官网看API文档的时候,会发现官网是这么应用a ...
- Vue.js 2.x笔记:状态管理Vuex(7)
1. Vuex简介与安装 1.1 Vuex简介 Vuex是为vue.js应用程序开发的状态管理模式,解决的问题: ◊ 组件之间的传参,多层嵌套组件之间的传参以及各组件之间耦合度过高问题 ◊ 不同状态中 ...
- Vuex以及axios
Vuex 简介 vuex是一个专门为Vue.js设计的集中式状态管理架构. 状态? 我们把它理解为在data中需要共享给其他组件使用的部分. Vuex和单纯的全局对象有以下不同: 1.Vuex 的状态 ...
- 09:vuex组件间通信
1.1 vuex简介 官网:https://vuex.vuejs.org/zh/guide/ 参考博客:https://www.cnblogs.com/first-time/p/6815036.htm ...
- Vuex以及axios 看这个
vuex -- 安装 npm i vuex -- 配置 -- 导入vuex import vuex from "vuex" -- vue使用vuex ...
- 详解Vuex常见问题、深入理解Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. 状态?我把它理解为在data中的属性需要共 ...
- Vuex+axios
Vuex+axios Vuex简介 vuex是一个专门为Vue.js设计的集中式状态管理架构. 状态? 我们把它理解为在data中需要共享给其他组件使用的部分. Vuex和单纯的全局对象有以下不同 ...
随机推荐
- centos7服务器监控之nmon
一.下载nmon 根据系统类型下载相应的版本: http://nmon.sourceforge.net/pmwiki.php?n=Site.Download 目前大多数服务器使用的centos7系统, ...
- 【1期】Java必知必会之一
面试官:线程池那些事儿 面试官:new 一个对象有哪两个过程?
- MSYQL主从复制-Gtid方式
目录 1.MYSQL主从复制-Gtid方式 1.环境准备 2.Master配置 3.Slave配置 4.报错&解决 我叫张贺,贪财好色.一名合格的LINUX运维工程师,专注于LINUX的学习和 ...
- Fiddler修改请求数据
截断方法一: 在菜单中选择“Rules”->“Automatic Breakpoint”->“Before Requests”,这种方式会截断所有Request请求. 2.浏览器打开站点, ...
- <Math> 29 365
29. Divide Two Integers class Solution { public int divide(int dividend, int divisor) { if(dividend ...
- Fuzzy finder(fzf+vim) 使用入门指南
今天无意中尝试了fzf,才发现这个工具的威力无穷,毕竟是非常好的工具,第一次都把它的优点都释放出来也不现实,先熟悉一下吧,后面在实战中再不断地学习总结. 它是什么: Fuzzy finder 是一款使 ...
- DFS(四):剪枝策略
顾名思义,剪枝就是通过一些判断,剪掉搜索树上不必要的子树.在采用DFS算法搜索时,有时候我们会发现某个结点对应的子树的状态都不是我们要的结果,这时候我们没必要对这个分支进行搜索,砍掉这个子树,就是剪枝 ...
- php-laravel框架用户验证(Auth)模块解析(一)
一.初始化 使用php artisan命令进行初始化:php artisan make:auth 和 php artisan migrate(该命令会生成users表.password_resets表 ...
- C#实现数据回滚,A事件和B事件同时执行,其中任何一个事件执行失败,都会返回失败
/// <summary> /// 执行数据库回滚操作,用于sql语句执行失败后,恢复执行前的数据 /// </summary> /// <param name=&quo ...
- 【转】ASP.NET Core 如何设置发布环境
在ASP.NET Core中自带了一些内置对象,可以读取到当前程序处于什么样的环境当中,比如在ASP.NET Core的Startup类的Configure方法中,我们就会看到这么一段代码: publ ...