组件状态管理
state :驱动应用的数据源
view :以声明方式将state映射到视图
actions :响应在view上的用户输入导致的状态变化
new Vue({
// state
data () {
return {
count: 0
}
},
// view
template: `<div>{{ count }}</div>`,
// actions
methods: {
increment () {
this.count++
}
}
})
组件通信方式
父传子
子组件中通过props接受数据,父组件中给子组件通过相应属性传值
子传父
$emit $on
不相关组件
因为组件不相关,所以创建一个eventbus来处理通信
其他方式
$root $parent $children $refs(不推荐,只有项目很小时才好使用)
Vuex
Vuex是专门为Vue设计的状态管理库,采用集中式的方式存储需要共享的状态,作用是进行状态管理,解决复杂组件通信和数据共享
State
单一状态树,集中存储所有状态数据,并且是响应式的
getter
类似于组件中的计算属性,如果想对state中的数据做简单处理并加以展示,就可以使用getter
mutation
状态(state)的修改必须通过提交mutation,mutation必须是同步执行,这样可以保证收集到所有的状态修改
action
提供异步操作
module
把单一状态树拆分成多个模块,每个模块可以拥有自己的mutation,action,getter,甚至是嵌套子模块
简单模拟Vuex
let _Vue = null;//存储 install 获取的 vue 构造函数
class Store {
construnctor (options) {
const {
state = {},
getters = {},
mutations = {},
actions = {}
} = options;
this.state = _Vue.observable(state);
this.getters = Object.create(null);
Object.keys(getters).forEach(key => {
Object.defineProperty(this.getters, key, {
get: () => {getters[key](state)}
})
})
this._mutations = mutations;
this._actions = actions;
}
commit (type, payload) {
this._mutations[type](this.state, payload);
}
dispatch (type,payload) {
this._actions[type](this, payload);
}
}
function install (Vue) {
_Vue = Vue;
//通过混入 beforeCreate 来获取 vue 实例
_Vue.mixin({
beforeCreate () {
if (this.$options.store) {
_Vue.prototype.$store = this.$options.store;
}
}
})
}
export default {
Store,
install
}