组件内的状态管理流程
Vue 最核心的两个功能:数据驱动和组件化。 组件化开发给我们带来了:
更快的开发效率
更好的可维护性
每个组件都有自己的状态、视图和行为等组成部分。
new Vue({
// state
data () {
return {
count: 0
} },
// view
template: `
<div>{{ count }}</div>
`,
// actions
methods: {
increment () {
this.count++
} }
})
状态管理包含以下几部分:
state,驱动应用的数据源;
view,以声明方式将 state 映射到视图;
actions,响应在 view 上的用户输入导致的状态变化。
组件间通信方式
大多数场景下的组件都并不是独立存在的,而是相互协作共同构成了一个复杂的业务功能。
在 Vue 中为不同的组件关系提供了不同的通信规则。
父组件给子组件传值
子组件中通过 props 接收数据
父组件中给子组件通过相应属性传值
// 父组件
<child title="My journey with Vue"></child>
// 子组件
<template>
<div>
<h1>Props Down Child</h1>
<h2>{{ title }}</h2>
</div>
</template>
<script>
export default {
// props: ['title'],
props: {
title: String
}
}
</script>
子组件给父组件传值
// 父组件
<template>
<div>
<h1 :style="{ fontSize: hFontSize + 'em'}">Event Up Parent</h1>
这里的文字不需要变化
<child :fontSize="hFontSize" v-on:enlargeText="enlargeText"></child>
<child :fontSize="hFontSize" v-on:enlargeText="enlargeText"></child>
<child :fontSize="hFontSize" v-on:enlargeText="hFontSize += $event"></child>
</div>
</template>
<script>
import child from './02-Child'
export default {
components: {
child
},
data () {
return {
hFontSize: 1
}
},
methods: {
enlargeText (size) {
this.hFontSize += size
}
}
}
</script>
// 子组件
<template>
<div>
<h1 :style="{ fontSize: fontSize + 'em' }">Props Down Child</h1>
<button @click="handler">文字增大</button>
</div>
</template>
<script>
export default {
props: {
fontSize: Number
},
methods: {
handler () {
this.$emit('enlargeText', 0.1)
}
}
}
</script>
不相关组件之间传值
// eventbus.js
import Vue from 'vue'
export default new Vue()
// 组件1
<template>
<div>
<h1>Event Bus Sibling01</h1>
<div class="number" @click="sub">-</div>
<input type="text" style="width: 30px; text-align: center" :value="value">
<div class="number" @click="add">+</div>
</div>
</template>
<script>
import bus from './eventbus'
export default {
props: {
num: Number
},
created () {
this.value = this.num
},
data () {
return {
value: -1
}
},
methods: {
sub () {
if (this.value > 1) {
this.value--
bus.$emit('numchange', this.value)
}
},
add () {
this.value++
bus.$emit('numchange', this.value)
}
}
}
</script>
// 组件2
<template>
<div>
<h1>Event Bus Sibling02</h1>
<div>{{ msg }}</div>
</div>
</template>
<script>
import bus from './eventbus'
export default {
data () {
return {
msg: ''
}
},
created () {
bus.$on('numchange', (value) => {
this.msg = `您选择了${value}件商品`
})
}
}
</script>
其他常见通信方式:
$root
$parent
$children
$refs
父组件直接访问子组件: 通过 ref 获取子组件
ref 有两个作用:
如果你把它作用到普通 HTML 标签上,则获取到的是 DOM
如果你把它作用到组件标签上,则获取到的是组件实例
// 父组件
<template>
<div>
<h1>ref Parent</h1>
<child ref="c"></child>
</div>
</template>
<script>
import child from './04-Child'
export default {
components: {
child
},
mounted () {
this.$refs.c.focus()
this.$refs.c.value = 'hello input'
}
}
</script>
// 子组件
<template>
<div>
<h1>ref Child</h1>
<input ref="input" type="text" v-model="value">
</div>
</template>
<script>
export default {
data () {
return {
value: ''
}
},
methods: {
focus () {
this.$refs.input.focus()
}
}
}
</script>
$refs 只会在组件渲染完成之后生效,并且它们不是响应式的。这仅作为一个用于直接操作子组 件的“逃生舱”——你应该避免在模板或计算属性中访问 $refs 。
简易的状态管理方案
如果多个组件之间要共享状态(数据),使用上面的方式虽然可以实现,但是比较麻烦,而且多个组件之 间互相传值很难跟踪数据的变化,如果出现问题很难定位问题。
当遇到多个组件需要共享状态的时候,典型的场景:购物车。我们如果使用上述的方案都不合适,我们 会遇到以下的问题:
多个视图依赖于同一状态。
来自不同视图的行为需要变更同一状态。
对于问题一,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。
对于问题二,我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这 些模式非常脆弱,通常会导致无法维护的代码。
因此,我们为什么不把组件的共享状态抽取出来,以一个全局单例模式管理呢?在这种模式下,我们的 组件树构成了一个巨大的“视图”,不管在树的哪个位置,任何组件都能获取状态或者触发行为!
我们可以把多个组件的状态,或者整个程序的状态放到一个集中的位置存储,并且可以检测到数据的更 改。你可能已经想到了 Vuex。
这里我们先以一种简单的方式来实现:
首先创建一个共享的仓库 store 对象
export default {
debug: true,
state: {
user: {
name: 'xiaomao',
age: 18,
sex: '男'
}
},
setUserNameAction (name) {
if (this.debug) {
console.log('setUserNameAction triggered:', name)
}
this.state.user.name = name
}
}
把共享的仓库 store 对象,存储到需要共享状态的组件的 data 中
// 组件A
<template>
<div>
<h1>componentA</h1>
user name: {{ sharedState.user.name }}
<button @click="change">Change Info</button>
</div>
</template>
<script>
import store from './store'
export default {
methods: {
change () {
store.setUserNameAction('componentA')
}
},
data () {
return {
privateState: {},
sharedState: store.state
}
}
}
</script>
// 组件 B
<template>
<div>
<h1>componentB</h1>
user name: {{ sharedState.user.name }}
<button @click="change">Change Info</button>
</div>
</template>
<script>
import store from './store'
export default {
methods: {
change () {
store.setUserNameAction('componentB')
}
},
data () {
return {
privateState: {},
sharedState: store.state
}
}
}
</script>
接着我们继续延伸约定,组件不允许直接变更属于 store 对象的 state,而应执行 action 来分发 (dispatch) 事件通知 store 去改变,这样最终的样子跟 Vuex 的结构就类似了。这样约定的好处是,我 们能够记录所有 store 中发生的 state 变更,同时实现能做到记录变更、保存状态快照、历史回滚/时光 旅行的先进的调试工具。
什么是 Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
- Vuex 是专门为 Vue.js 设计的状态管理库
- 它采用集中式的方式存储需要共享的数据
- 从使用角度,它就是一个 JavaScript 库
- 它的作用是进行状态管理,解决复杂组件通信,数据共享
什么情况下使用 Vuex
非必要的情况下不要使用 Vuex
大型的单页应用程序
- 多个视图依赖于同一状态
- 来自不同视图的行为需要变更同一状态
注意:Vuex 不要滥用,不符合以上需求的业务不要使用,反而会让你的应用变得更麻烦。
官方文档:
Vuex 可以帮助我们管理共享状态,并附带了更多的概念和框架。这需要对短期和长期效益进行权 衡。
如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用 够简单,您最好不要使用 Vuex。一个简单的 store 模式就足够您所需了。但是,如果您需要构建 一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然 的选择。引用 Redux 的作者 Dan Abramov 的话说就是:Flux 架构就像眼镜:您自会知道什么时候需要它。
Vuex 的核心概念
State 管理全局状态,把状态绑定到组件,渲染到视图上,
用户在视图上做交互操作,通过 Dispatch 分发到 Actions,
在 Actions 可以做异步请求,获取到请求到的数据,
通过 Commit 提交到 Mustations,Mustations 记录状态的更改,
Mustations 必须是同步的,状态的更改,必须通过 Mustations,
这样可以通过 Mustations 追踪到所有状态的变化。
Store:
Store 是 Vuex 应用的核心,每一个应用仅有一个 Store,Store是一个容器,包含应用中的大部分状态,不能直接改变状态,要通过提交 Mustations 的方式来改变状态。
State:
State 是状态,保存在 Store 中,因为 Store 是唯一的,所以 State 也是唯一的,称为 单一状态树,所有的状态保存在State中,会难以维护,可以使用模块,State 是响应式的。
Getter:
Getter 是 Vuex 中的计算属性,方便从一个属性派生出其他的值,可以对计算的结果进行缓存,只有当依赖的状态发生改变时,才会进行重新计算。
Mustation:
状态的变化必须通过提交 Mustation 来完成。
Action:
Action 可以进行异步的操作,改变状态时,必须通过 Mustation。
Module:
由于使用 单一状态树,应用的所有状态会集中到一个比较大的对象中,当应用变得非常复杂时,Store 对象就会变得非常臃肿,所以需要将 Store 分割成不同的模块,每个模块都包含 State、Mustation、Action、Getter。
Vuex 代码结构
导入 Vuex
注册 Vuex
注入 store 到 Vue 实例
注入 store 到 Vue 实例
State
Vuex 使用单一状态树,用一个对象就包含了全部的应用层级状态。
使用 mapState 简化 State 在视图中的使用,mapState 返回计算属性。
mapState 有两种使用的方式:
接收数组参数
// mapState 方法是 vuex 提供的,所以使用前要先导入
import { mapState } from 'vuex'
// mapState 返回名称为 count 和 msg 的计算属性
// 在模板中直接使用 count 和 msg
computed: {
...mapState(['count', 'msg']),
}
接收对象参数
如果当前视图中已经有了 count 和 msg,如果使用上述方式的话会有命名冲突,解决的方式:
// mapState 方法是 vuex 提供的,所以使用前要先导入
import { mapState } from 'vuex'
// 通过传入对象,可以重命名返回的计算属性
// 在模板中直接使用 num 和 message
computed: {
...mapState({
num: state => state.count,
message: state => state.msg
})
}
Getter
Getter 就是 store 中的计算属性,使用 mapGetter 简化视图中的使用
import { mapGetter } from 'vuex'
computed: {
...mapGetter(['reverseMsg']),
// 改名,在模板中使用 reverse
...mapGetter({
reverse: 'reverseMsg'
})
}
Mutation
<h2>Mutation</h2>
<!-- <button @click="$store.commit('increate', 2)">Mutation</button> -->
<button @click="increate(3)">Mutation</button>
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['increate']),
// 传对象解决重名的问题
...mapMutations({
increateMut: 'increate'
})
}
Action
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
<h2>Action</h2>
<!-- <button @click="$store.dispatch('increateAsync', 5)">Action</button> -->
<button @click="increateAsync(6)">Action</button>
import { mapActions } from 'vuex'
methods: {
...mapActions(['increate']),
// 传对象解决重名的问题
...mapActions({
increateAction: 'increate'
})
}
Module
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import products from './modules/products'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
products
}
})
store\modules\products.js
const state = {
products: [
{ id: 1, title: 'iPhone 11', price: 8000 },
{ id: 2, title: 'iPhone 12', price: 10000 }
]
}
const getters = {}
const mutations = {
setProducts (state, payload) {
state.products = payload
}
}
const actions = {}
export default {
namespaced: true,
state,
getters,
mutations,
actions
}
import { mapState, mapActions } from 'vuex'
export default {
name: 'ProductList',
computed: {
...mapState('products', ['products'])
},
methods: {
...mapActions('products', ['getAllProducts'])
},
created () {
this.getAllProducts()
}
}
本地存储
利用 vuex 提供的插件保存 vuex 数据,在属性浏览器后,vuex 的数据不会丢失
import Vue from 'vue'
import Vuex from 'vuex'
import products from './modules/products'
import cart from './modules/cart'
Vue.use(Vuex)
const myPlugin = store => {
store.subscribe((mutation, state) => {
if (mutation.type.startsWith('cart/')) {
window.localStorage.setItem('cart-products', JSON.stringify(state.cart.cartProducts))
}
})
}
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
products,
cart
},
plugins: [myPlugin]
})
store/modules
const state = {
cartProducts: JSON.parse(window.localStorage.getItem('cart-products')) || [],
test: 'cart test'
}
Vuex 模拟实现
实现思路
实现 install 方法:
- Vuex 是 Vue 的一个插件,所以和模拟 VueRouter 类似,先实现 Vue 插件约定的 install 方法
实现 Store 类:
- 实现构造函数,接收 options
- state 的响应化处理
- getter 的实现
- commit、dispatch 方法
let _Vue = null
function install (Vue) {
_Vue = Vue
_Vue.mixin({
beforeCreate () {
if (this.$options.store) {
Vue.prototype.$store = this.$options.store
}
}
})
}
class Store {
constructor (options) {
const {
state = {},
getters = {},
mutations = {},
actions = {}
} = options
this.state = _Vue.observable(state)
// 此处不直接 this.getters = getters,是因为下面的代码中要方法 getters 中的 key
// 如果这么写的话,会导致 this.getters 和 getters 指向同一个对象
// 当访问 getters 的 key 的时候,实际上就是访问 this.getters 的 key 会触发 key 属性
的 getter
// 会产生死递归
this.getters = Object.create(null)
Object.keys(getters).forEach(key => {
Object.defineProperty(this.getters, key, {
get: () => getters[key](this.state)
})
})
this.mutations = mutations
this.actions = actions
}
commit (type, payload) {
this.mutations[type](this.state, payload)
}
dispatch (type, payload) {
this.actions[type](this, payload)
}
}
// 导出模块
export default {
Store,
install
}
1