vuex详解

参考网站:开始 | Vuex

Vuex 和单纯的全局对象有以下两点不同:

  1. Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。(其他组使用相同状态的组件会自动更新,不想全局变量要被调用相应的地方才更新)

  2. 你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。

使用示例

创建store

// 如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)

const store = new Vuex.Store({
  // 提供一个初始 state 对象和一些 mutation
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

组件调用相应状态

// 通过 store.state 来获取状态对象
store.commit('increment')

// 通过 store.commit 方法触发状态变更
console.log(store.state.count) // -> 1

通过提交 mutation 的方式,而非直接改变 store.state.count,是因为我们想要更明确地追踪到状态的变化

由于 store 中的状态是响应式的,在组件中调用 store 中的状态简单到仅需要在计算属性中返回即可。触发变化也仅仅是在组件的 methods 中提交 mutation。

state(初始化数据对象类似vue里的data属性)

基础

如实例所讲 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态

根组件“注入”

情景:在模块化的构建系统中,在每个需要使用 state 的组件中需要频繁地导入,并且在测试组件时需要模拟状态。

解决方案:通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。(子组件更新还算是通过compute属性计算)

const app = new Vue({
  el: '#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})

// 子组件访问状态
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}

mapState 辅助函数

场景:当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。

使用示例:computed: mapState({ '状态名'})

// 在单独构建的版本中引入辅助函数为 Vuex.mapState
import { 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
    }
  })
}

Getter(获取state的数据值,可对获取的值做一定操作,有缓存)

场景:有时候我们需要从 store 中的 state 中派生出一些状态(如从一串数字中获取大于5的数字)

解决方法:Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

代码示例:

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    // state为第一个参数
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    },
    // getter自身可为第二个参数
    doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
    }
  }
})

// 通过属性访问
computed: {
  doneTodos() {
    return this.$store.getters.doneTodos
  },
  doneTodosCount() {
    return this.$store.getters.doneTodosCount
  }
}

 getter 传参

注意:getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。

代码示例:

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

// 通过方法访问
computed: {
  doneTodos() {
    return this.$store.getters.getTodoById(2)
  },
}

getter的mapGetters 辅助函数

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

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
      doneCount: 'doneTodosCount'
      // ...
    ])
  }
}

Mutation(同步,更改state的值)

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。在子组件的methods方法中调用

每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    // 类型为 increment,后面是该类型下的回调函数
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})

// 不能直接调用一个 mutation handler。这个选项更像是事件注册:“当触发一个类型为 increment 的 mutation 时,调用此函数。”
 methods: {
    a(){
     store.commit('increment')
    }
 }

mutation 的 载荷

你可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload)

mutations: {
  increment (state, n) {
    state.count += n
  }
}

// 调用

methods: {
    a(){
       store.commit('increment', {
          amount: 10
        })
    }
 }

// 参数也可以是个对象
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
// 调用
 methods: {
    a(){
        store.commit('increment', {
           amount: 10
        })
    }
 }

Mutation 需遵守 Vue 的响应规则

  1. 最好提前在你的 store 中初始化好所有所需属性。

  2. Mutation 必须是同步函数(放置嵌套的mutation因获取不到上一不得值的根性,而更新失误)

  3. 当需要在对象上添加新属性时,你应该

  • 使用 Vue.set(obj, 'newProp', 123), 或者

  • 以新对象替换老对象。例如,利用 stage-3 的对象展开运算符我们可以这样写:

    // ...为es6的扩展运算符
    state.obj = { ...state.obj, newProp: 123 }

 mapMutations 辅助函数

你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 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')`
    })
  }
}

使用常量替代 Mutation 事件类型

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

用不用常量取决于你——在需要多人协作的大型项目中,这会很有帮助。但如果你不喜欢,你完全可以不这样做。

// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'

const store = new Vuex.Store({
  state: { ... },
  mutations: {
    // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
    [SOME_MUTATION] (state) {
      // mutate state
    }
  }
})

Action(异步,更改state的值)

 由于mutation 必须同步执行,所以我们可以在 action 内部执行异步操作

区别:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。

分发 Action(触发action)

Action 通过 store.dispatch 方法触发:

store.dispatch('increment')

Actions 支持同样的载荷方式和对象方式进行分发

// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

mapActions 辅助函数

你在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

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')`
    })
  }
}

组合 Action

首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:

actions: {
  // 我们会经常用到 ES2015 的 参数解构 来简化代码(特别是我们需要调用 commit 很多次的时候)
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  },
  // 在另外一个 action 中也可以
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  } 
  // async/await写法
  async actionD ({ commit }) {
    commit('gotData', await getData())
  },
  async actionD ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  },
}

// 调用

store.dispatch('actionA').then(() => {
  // ...
})

Module

场景:多模块开发时,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = createStore({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

问题集锦

1.当store变更后,刷新页面会怎样?

刷新后,store回还原,解决方法:通过session或者localstorage存储下来,没次读取前先查session或者localstorage看是有有值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值