1)多个视图依赖于同一状态vue
2)来自不一样视图的行为须要变动同一状态vuex
Vuex则是把组件的共享状态抽取出来,以一个全局单例模式管理npm
同时,经过定义和隔离状态管理中的各类概念并强制遵照必定的规则,代码变得更结构化、易维护数组
以上就是vuex的思想缓存
store
中存储的各个状态。store
中状态的执行者, 只能是同步操做 。import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
getter: {
doneTodos: (state, getters) => {
return state.todos.filter(todo => todo.done)
}
},
mutations: {
increment (state, payload) {
state.count++
}
},
actions: {
addCount(context) {
// 能够包含异步操做
// context 是一个与 store 实例具备相同方法和属性的 context 对象
}
}
})
// 注入到根实例
new Vue({
el: '#app',
// 把 store 对象提供给 “store” 选项,这能够把 store 的实例注入全部的子组件
store,
template: '<App/>',
components: { App }
})
template: `<div>{{ count }}</div>`,app
computed: { count () { return this.$store.state.count // count 为某个状态 } }异步
}
模块化
const store = new Vuex.Store({ state: { todos: [ { id: 1, text: '...', done: true }, { id: 2, text: '...', done: false } ] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) } } })
经过属性访问
咱们能够很容易在任何组件中使用他
computed: { doneTodosCount () { return this.$store.getters.doneTodosCount } }
也能够经过让 getter 返回一个函数,来实现给 getter 传参。在对 store 里的数组进行查询时很是有用。函数
getters: { // ... getTodoById: (state) => (id) => { return state.todos.find(todo => todo.id === id) } }
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
注意:getter 在经过方法访问时,每次都会去进行调用,而不会缓存结果。this
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state) { // 变动状态 state.count++ } } })
// ...
mutations: {
increment (state, n) {
state.count += n
}
}
this.$store.commit('increment', 10)
其中,第一个参数是 state
,后面的参数是向 store.commit
传入的额外的参数,即 mutation 的 载荷(payload) 。
store.commit
方法的第一个参数是要发起的 mutation
类型名称,后面的参数均当作额外数据传入 mutation
定义的方法中。
规范的发起 mutation
的方式以下:
// 以载荷形式 store.commit('increment',{ amount: 10 //这是额外的参数 }) // 或者使用对象风格的提交方式 store.commit({ type: 'increment', amount: 10 //这是额外的参数 })
额外的参数会封装进一个对象,做为第二个参数传入 mutation
定义的方法中。
mutations: { increment (state, payload) { state.count += payload.amount } }
Action 异步方法(异步的更改状态)
actions: { actionA ({ commit }) { return new Promise((resolve, reject) => { setTimeout(() => { commit('someMutation') resolve() }, 1000) }) } }
Action与mutation的区别
action提交的是mutation,而不是直接变动状态
action能够包含任意异步操做,而mutation只能且必须是同步操做
因为使用单一状态树,应用的全部状态会集中到一个比较大的对象。当应用变得很是复杂时,store 对象就有可能变得至关臃肿。
这时咱们能够将 store 分割为 模块(module) ,每一个模块拥有本身的 state
、 getters
、 mutations
、 actions
、甚至是嵌套子模块——从上至下进行一样方式的分割。
代码示例:
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 的状态
欢迎各位大佬补充!