Vuex 学习记录

Vuex 状态管理模式+库

三部分。

1.状态 :来源

2.视图。:声明映射的状态

3.动作:状态可能因视图中的用户输入而改变的方式

把共同的状态抽取出来,作为一个全局单例模式管理。

从而构成一个巨大的视图,无论处于哪个位子都可以触发状态和行为。

通过定义隔离状态并强制遵守一定的规则,便于维护。

Vuex的核心是商店。

容纳应用程序状态的容器。

有两件事使得商店与全局对象不同:

1.商店是被动的,当Vue组件从中检索状态时,如果商店中的状态发生变化,将会对应反馈到相应的更新。

2.改变商店的状态的办法,唯一方法是,提交突变。

Vuex 创建一个商店的基本:

// Make sure to call Vue.use(Vuex) first if using a module system

const store = new Vuex.Store({

state: {

count: 0

},

mutations: {

increment (state) {

state.count++

}

}})

methods里面可以调用

store.commit('increment');

单一状态树

每一个应用仅仅包含一个Store 实例,作为唯一数据源,SSOT single source of truth

在组件中获得VUEX的状态,最好的办法就是用计算属性。

当对应的状态改变,会重新计算求值。

// 创建一个 Counter 组件const Counter = {

template: `<div>{{ count }}</div>`,

computed: {

count () {

return store.state.count

}

}}

这样需要频繁的导入,因此可以通过store选项,将跟组件注入到每一个子组件中。

const app = new Vue({

el: '#app',

// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件

store,

components: { Counter },

template: `

<div class="app">

<counter></counter>

</div>

`})

通过在根实例中注册store选项,该商店实例会注入到根组件下的所有子组件中,且子组件能通过this.$store访问到。让我们更新下Counter的实现:

const Counter = {

template: `<div>{{ count }}</div>`,

computed: {

count () {

return this.$store.state.count

}

}}

 

子组件能通过this.$store访问到。

mapState辅助函数

一个组件需要多个状态时候,计算属性会有些重复和冗余。

计算属性,让你少按几次键:

// 在单独构建的版本中辅助函数为 Vuex.mapStateimport { mapState } from 'vuex'

export default {

// ...

computed: mapState({

// 箭头函数可使代码更简练

count: state => state.count,

// 传字符串参数 'count' 等同于 `state => state.count`

countAlias: 'count',

// 为了能够使用 `this` 获取局部状态,必须使用常规函数

countPlusLocalState (state) {

return state.count + this.localCount

}

})}

经过 mapState 函数调用后的结果,如下所示:

import { mapState } from 'vuex'export default {

// ...

computed: {

count() {

return this.$store.state.count

},

countAlias() {

return this.$store.state['count']

},

countPlusLocalState() {

return this.$store.state.count + this.localCount

}

}}

同样mapState也可以传入一个字符串数组。

computed: mapState([

// 映射 this.count 为 store.state.count

'count'])

对象展开运算符:

将mapState与局部的计算属性混合使用。

computed: {

localComputed () { /* ... */ },

// 使用对象展开运算符将此对象混入到外部对象中

...mapState({

// ...

})}

 

Getter

当我们需要从状态中派生出一些状态。

可以使用getter。

Getter接受状态作为其第一个参数

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)

}

}})

Getter也可以接受其他getter作为第二个参数

getters: {

// ...

doneTodosCount: (state, getters) => {

return getters.doneTodos.length

}}

store.getters.doneTodosCount // -> 1

 

同时,Getter会暴露为store.getters的对象。

你可以直接通过store.getters.doneTodos来访问。

在计算属性中进行使用:

computed: {

doneTodosCount () {

return this.$store.getters.doneTodosCount

}}

可以通过getter返回函数进行传参,可以通过这样查找到里面通过ID或者其他要求得到的数据。有点像指定条件查询某一个元素这样。

getters: {

// ...

getTodoById: (state) => (id) => {

return state.todos.find(todo => todo.id === id)

}}

store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

需要注意的是, getter通过方法访问时,每次都会进行方法的调用,而且不会进行对缓存结果进行缓存。

mapGetter仅仅就是将store中的getter方法 映射到局部计算属性中去。

如果想将getter属性另外取一个名字,可以使用对象的形式。

mapGetters 辅助函数仅仅是将store中的getter映射到局部计算属性:

import { mapGetters } from 'vuex'

export default {

// ...

computed: {

// 使用对象展开运算符将 getter 混入 computed 对象中

...mapGetters([

'doneTodosCount',

'anotherGetter',

// ...

])

}}

如果你想将一个getter属性另取一个名字,使用对象形式:

mapGetters({

// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`

doneCount: 'doneTodosCount'})

突变

改变 VueX中的状态的办法是提交突变。

每一个突变都有一个字符串的事件类型和一个回调函数

这个回调函数就是我们实际进行状态更改的地方,并且它会接受状态作为第一个参数

const store = new Vuex.Store({

state: {

count: 1

},

mutations: {

increment (state) {

// 变更状态

state.count++

}

}})

当需要使用该突变的时候,需要使用

store.commit('increment');

同时可以像其中传入额外的参数,为突变的载荷(payload)

// ...

mutations: {

increment (state, n) {

state.count += n

}}

store.commit('increment', 10)

在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的变异会更易读:

// ...

mutations: {

increment (state, payload) {

state.count += payload.amount

}}

store.commit('increment', {

amount: 10})

 

 同时提交时,还支持另外一种方式为包含type属性的对象。

对象风格的提交方式

store.commit({

type: 'increment',

amount: 10})

处理器的部分是不变的。

同时突变仍然需要遵守响应的规则

1.最好一开始就初始化好相应的属性。

2.当需要为对象添加属性时候,Vue.set(obj,'newProp',123)

    或者以新代替老。

    state.obj={..state.obj,newProp:123}

使用常量代替突变事件类型

使用常量替代变异事件类型在各种Flux实现中是很常见的模式。这样可以使linter之类的工具发挥作用,同时把这些常量放在单独的文件中可以让你的代码合作者对整个app包含的变异一目了然:

// mutation-types.jsexport const SOME_MUTATION = 'SOME_MUTATION'

// store.jsimport Vuex from 'vuex'import { SOME_MUTATION } from './mutation-types'

const store = new Vuex.Store({

state: { ... },

mutations: {

// 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名

[SOME_MUTATION] (state) {

// mutate state

}

}})

突变必须是同步函数。

组件中提交突变:

使用到mapMutations:

可以在组件中使用this.$store.commit('xxx')提交变异,或者使用mapMutations辅助函数将组件中的方法映射为store.commit调用(需要在根节点注入store)。

import { mapMutations } from 'vuex'

export default {

// ...

methods: {

...mapMutations([

'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

// `mapMutations` 也支持载荷:

'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`

]),

...mapMutations({

add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`

})

}}

 

行动Action:

动作类似于突变,但是有所不同,

动作是提交变异,而不是直接改变状态。

动作可以包含任意异步操作。

让我们来注册一个简单的动作:

const store = new Vuex.Store({

state: {

count: 0

},

mutations: {

increment (state) {

state.count++

}

},

actions: {

increment (context) {

context.commit('increment')

}

}})

Action函数接受一个与store实例具有相同的方法和属性的context对象,可以通过 context ,context.commit提交变异,context.state,context.getters 来获得状态和 getters.

actions: {

increment ({ commit }) {

commit('increment')

}}

分发行动:

突变必须同步执行的限制,行动不受限制不受约束,可以在行动内部执行异步操作:

store.dispatch('increment')

我们可以在行动内部执行异步操作:

actions: {

incrementAsync ({ commit }) {

setTimeout(() => {

commit('increment')

}, 1000)

}}

来看一个更加实际的购物车示例,涉及到调用异步API分发多重变异

actions: {

checkout ({ commit, state }, products) {

// 把当前购物车的物品备份起来

const savedCartItems = [...state.cart.added]

// 发出结账请求,然后乐观地清空购物车

commit(types.CHECKOUT_REQUEST)

// 购物 API 接受一个成功回调和一个失败回调

shop.buyProducts(

products,

// 成功操作

() => commit(types.CHECKOUT_SUCCESS),

// 失败操作

() => commit(types.CHECKOUT_FAILURE, savedCartItems)

)

}}

this.$store.dispatch('xxx')

import { mapActions } from 'vuex'

export default {

// ...

methods: {

...mapActions([

'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

// `mapActions` 也支持载荷:

'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`

]),

...mapActions({

add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`

})

}}

???操作中的动作部分好多不懂 emm(后续补充)

组件仍然保留有局部状态。

Vuex不意味着你将所有的状态放入Vuex,如果有些状态严格属于单个组件,最好还是作为组件的局部状态。

模块

Vuex允许我们将商店分割模块。每一个模块拥有自己的状态,变异,动作,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 的状态

模块的局部状态

在模块内部,接受的第一个参数是模块局部状态state对象。

同样,对于模块内部的动作,局部状态通过context.state暴露出来,根节点状态则为context.rootState

const moduleA = {

// ...

actions: {

incrementIfOddOnRootSum ({ state, commit, rootState }) {

if ((state.count + rootState.count) % 2 === 1) {

commit('increment')

}

}

}}

对于模块内部的getter,根节点状态会作为第三个参数暴露出来:

const moduleA = {

// ...

getters: {

sumWithRootCount (state, getters, rootState) {

return state.count + rootState.count

}

}}

命名空间

模块具有更高的封装性和复用性。通过namespaced:true。

你在使用模块内容(模块资产)时不需要在同一模块内额外添加空间名前缀。更改namespaced属性后不需要修改模块内的代码。

const store = new Vuex.Store({

modules: {

account: {

namespaced: true,

// 模块内容(module assets)

state: { ... }, // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响

getters: {

isAdmin () { ... } // -> getters['account/isAdmin']

},

actions: {

login () { ... } // -> dispatch('account/login')

},

mutations: {

login () { ... } // -> commit('account/login')

},

// 嵌套模块

modules: {

// 继承父模块的命名空间

myPage: {

state: { ... },

getters: {

profile () { ... } // -> getters['account/profile']

}

},

// 进一步嵌套命名空间

posts: {

namespaced: true,

state: { ... },

getters: {

popular () { ... } // -> getters['account/posts/popular']

}

}

}

}

}})

带命名空间的模块内访问全局内容

参数传给dispatchcommit即可。

modules: {

foo: {

namespaced: true,

getters: {

// 在这个模块的 getter 中,`getters` 被局部化了

// 你可以使用 getter 的第四个参数来调用 `rootGetters`

someGetter (state, getters, rootState, rootGetters) {

getters.someOtherGetter // -> 'foo/someOtherGetter'

rootGetters.someOtherGetter // -> 'someOtherGetter'

},

someOtherGetter: state => { ... }

},

actions: {

// 在这个模块中, dispatch 和 commit 也被局部化了

// 他们可以接受 `root` 属性以访问根 dispatch 或 commit

someAction ({ dispatch, commit, getters, rootGetters }) {

getters.someGetter // -> 'foo/someGetter'

rootGetters.someGetter // -> 'someGetter'

dispatch('someOtherAction') // -> 'foo/someOtherAction'

dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'

commit('someMutation') // -> 'foo/someMutation'

commit('someMutation', null, { root: true }) // -> 'someMutation'

},

someOtherAction (ctx, payload) { ... }

}

}}

带命名空间的绑定函数

当使用mapStatemapGettersmapActions状语从句:mapMutations这些函数来绑定带命名空间的模块时,写起来可能比较繁琐:

computed: {

...mapState({

a: state => state.some.nested.module.a,

b: state => state.some.nested.module.b

})},

methods: {

...mapActions([

'some/nested/module/foo', // -> this['some/nested/module/foo']()

'some/nested/module/bar' // -> this['some/nested/module/bar']()

])}

对于这种情况,你可以将模块的空间名称字符串作为第一个参数传递给上述函数,这样所有绑定都会自动将该模块作为上下文于是上面的例子可以简化为:

computed: {

...mapState('some/nested/module', {

a: state => state.a,

b: state => state.b

})},

methods: {

...mapActions('some/nested/module', [

'foo', // -> this.foo()

'bar' // -> this.bar()

])}

模块动态注册

store.registerModule

模块动态注册

在 store 创建之后,你可以使用 store.registerModule 方法注册模块:

// 注册模块 `myModule`

store.registerModule('myModule', {

// ...})// 注册嵌套模块 `nested/myModule`

store.registerModule(['nested', 'myModule'], {

// ...})

之后就可以通过 store.state.myModule  store.state.nested.myModule 访问模块的状态。

模块动态注册使得其他Vue插件可以在store中附加新模块的方式来访问Vuex。

store.registerModule 来注册模块。

store.unregisterModule来卸载模块。

对于保留过去的state 可以通过preserveState来将其归档。

store.registerModule('a', module, { preserveState: true })

模块重用

对于一个模块多个实例,其中的state类似 data的问题,同样采用return 一个函数的做法。

state(){

    return {

        foo: 'bar'

    }

}

用一个函数来声明模块状态,避免模块之间的相互污染。。

 

 

项目结构

1.应用层的状态分别集中在单个store中。

2.mutation 是改变状态的唯一方法,过程是同步的。

3.异步逻辑的封装应该封装到action里面。

插件

vuex 的store 接受plugins 的选项,从而暴露出mutation 的钩子。

 

const myPlugin = store => {

// 当 store 初始化后调用

store.subscribe((mutation, state) => {

// 每次 mutation 之后调用

// mutation 的格式为 { type, payload }

})}

然后像这样使用:

const store = new Vuex.Store({

// ...

plugins: [myPlugin]})

 

提交mutation:

实际上 createPlugin 方法可以有更多选项来完成复杂任务

生成state快照。

生成状态快照的插件应该只在开发阶段使用,使用 webpack 或 Browserify,让构建工具帮我们处理:

const store = new Vuex.Store({

// ...

plugins: process.env.NODE_ENV !== 'production'

? [myPluginWithSnapshot]

: []})

上面插件会默认启用。在发布阶段,你需要使用 webpack 的 DefinePlugin 或者是 Browserify 的 envify 使 process.env.NODE_ENV !== 'production'  false

内置 Logger 插件

Vuex 自带一个日志插件用于一般的调试:

import createLogger from 'vuex/dist/logger'

const store = new Vuex.Store({

plugins: [createLogger()]})

createLogger 函数有几个配置项:

const logger = createLogger({

collapsed: false, // 自动展开记录的 mutation

filter (mutation, stateBefore, stateAfter) {

// 若 mutation 需要被记录,就让它返回 true 即可

// 顺便,`mutation` 是个 { type, payload } 对象

return mutation.type !== "aBlacklistedMutation"

},

transformer (state) {

// 在开始记录之前转换状态

// 例如,只返回指定的子树

return state.subTree

},

mutationTransformer (mutation) {

// mutation 按照 { type, payload } 格式记录

// 我们可以按任意方式格式化

return mutation.type

},

logger: console, // 自定义 console 实现,默认为 `console`})

严格模式

在严格模式下,状态的更变如果不是mutation提交的话,就会报错。

const store = new Vuex.Store({

// ...

strict: true})

开发环境与发布环境

const store = new Vuex.Store({

// ...

strict: process.env.NODE_ENV !== 'production'})

表单处理

对于input 的v-model 属于非mutation触发的改变,应该怎么做呢?

<input :value="message" @input="updateMessage">

// ...

computed: {

...mapState({

message: state => state.obj.message

})},

methods: {

updateMessage (e) {

this.$store.commit('updateMessage', e.target.value)

}}

// ...

mutations: {

updateMessage (state, message) {

state.obj.message = message

}}

双向绑定的计算属性:

<input v-model="message">

// ...

computed: {

message: {

get () {

return this.$store.state.obj.message

},

set (value) {

this.$store.commit('updateMessage', value)

}

}}

通过get,set来计算属性。 

测试

(未看)

热重载

     对于 mutation 和模块,你需要使用 store.hotUpdate() 方法:

// store.jsimport Vue from 'vue'import Vuex from 'vuex'import mutations from './mutations'import moduleA from './modules/a'

Vue.use(Vuex)

const state = { ... }

const store = new Vuex.Store({

state,

mutations,

modules: {

a: moduleA

}})

if (module.hot) {

// 使 action 和 mutation 成为可热重载模块

module.hot.accept(['./mutations', './modules/a'], () => {

// 获取更新后的模块

// 因为 babel 6 的模块编译格式问题,这里需要加上 `.default`

const newMutations = require('./mutations').default

const newModuleA = require('./modules/a').default

// 加载新模块

store.hotUpdate({

mutations: newMutations,

modules: {

a: newModuleA

}

})

})}

猜你喜欢

转载自blog.csdn.net/qq_37021554/article/details/83241942
今日推荐