vuex学习笔记

vuex

  • 状态管理器
  • 作为应用中所有组件的中央储存
  • 只能以预定的方式去操作状态
  • 把所有组件共享的状态抽取出来作为全局的单例,使得任何组件都能访问状态、触发动作

初始化

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

注入到App

const app = new Vue({
  el: '#app',
  // 会自动注入到每个子组件
  store: store
  // ...
})

// 接下来就可以在每个组件里使用$store来代替this.store

State

  • 在组件中使用State里的数据(注意它是响应式的)
    const Counter = {
    template: <div>{{ count }}</div>,
    computed: {
    count () {
    return $store.state.count
    }
    }
    }

  • 使用mapState一次性做几个computed
    import { mapState } from 'vuex'

    export default {
      computed: {
        otherComputed() {},
        ...mapState({  // ES2015的新语法,把对象分散为多个属性
          count: state => state.count,  // 接收的state参数里存了各种东西
          // 上下两句话二选一
          countAlias: 'count',
        })
      }
    }
    
    // 如果属性的名字一样,可以传名称的数组给mapState
    mapState(['count'])
    
  • 但并非所有状态都无脑放State里,也可以放组件自己的储存里

Getters

  • 在全局提供可复用的"computed属性"供各个组件调用

  • 简单使用
    const store = new Vuex.Store({
    state: {
    todos: [
    { id: 1, text: '...', done: true },
    { id: 2, text: '...', done: false }
    ]
    },
    getters: {
    doneTodos: state => { // 接收第一个参数state用于调用state里的数据,第二个参数getters用于使用其他getter的结果
    return state.todos.filter(todo => todo.done)
    }
    }
    })

    computed: {
      doneTodosCount () {
        return this.$store.getters.doneTodosCount  // 通过$store.getters调用
      }
    }
    
  • 同样也有mapGetters
    import { mapGetters } from 'vuex'

    export default {
      computed: {
        ...mapGetters([
          'doneTodosCount',
          'anotherGetter',
        ])
      }
    }
    
    // 如果想改名字可以用对象
    ...mapGetters({
      doneCount: 'doneTodosCount'
    })Mutations
    

Mutations

  • 提交Mutation是修改State的唯一方法

  • 类似于事件(events)

  • 基本使用
    const store = new Vuex.Store({
    state: {
    count: 1
    },
    mutations: {
    increment (state, n) { // 接收state作为第一个参数,后面是commit时候传递过去的参数
    // mutate state
    state.count++
    }
    }
    })

    // 这样调用(实践中通常传一个对象作为第二个参数,这样可以传递多个属性)
    store.commit('increment', 10)  // 第一个参数是mutation名,而10就是上面的n
    
    //    另外一种写法,此时整个对象会作为mutation函数的第二个参数
    store.commit({
      type: 'increment',
      amount: 10
    })
    
  • 使用mapMutations
    import { mapMutations } from 'vuex'

    export default {
      // ...
      methods: {
        ...mapMutations([  // 数组形式
          'increment' // this.increment() = this.$store.commit('increment')
        ]),
        ...mapMutations({  // 对象形式
          add: 'increment' // this.add() = this.$store.commit('increment')
        })
      }
    }
    
  • 注意事项:

    • 在一开始的时候初始化State的每个属性
    • 对对象添加属性时应该使用Vue.set方法
    • Mutation应当是同步的,同时也不应该在异步方法里调用Mutation,否则会导致分不清先后顺序

Actions

  • 提交的是Mutation而不是State

  • 可以包含异步操作

  • 简单使用
    const store = new Vuex.Store({
    state: {
    count: 0
    },
    mutations: {
    increment (state) {
    state.count++
    }
    },
    actions: {
    increment (context) { // context有着store的所有属性和方法
    context.commit('increment')
    }
    }
    })

    // 使用解构来简化写法
    actions: {
      increment ({ commit }) {
        commit('increment')
      }
    }
    
  • 分发 Actions
    actions: {
    incrementAsync ({ commit }, payload) { // 进行异步操作。第二个参数是dispatch给他的
    setTimeout(() => {
    commit('increment')
    }, 1000)
    }
    }

    // 两种触发方式
    store.dispatch('incrementAsync', {
      amount: 10
    })
    store.dispatch({
      type: 'incrementAsync',
      amount: 10
    })
    
  • 使用样例
    actions: {
    checkout ({ commit, state }, payload) {
    const savedCartItems = [...state.cart.added]
    // 做一些异步操作例如清空购物车
    commit(types.CHECKOUT_REQUEST)
    shop.buyProducts(
    products,
    // 成功回调
    () => commit(types.CHECKOUT_SUCCESS),
    // 失败回调
    () => commit(types.CHECKOUT_FAILURE, savedCartItems)
    )
    }
    }

  • mapActions
    import { mapActions } from 'vuex'

    export default {
      // ...
      methods: {
        ...mapActions([
          'increment' // this.increment() = this.$store.dispatch('increment')
        ]),
        ...mapActions({
          add: 'increment' // this.add() = this.$store.dispatch('increment')
        })
      }
    }
    
  • 处理异步的回调
    actions: {
    actionA ({ commit }) {
    return new Promise((resolve, reject) => { // 返回了一个Promise
    setTimeout(() => {
    commit('someMutation')
    resolve() // 函数内做好事情后resolve
    }, 1000)
    })
    },
    actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => { // 这里用then
    commit('someOtherMutation')
    })
    }
    }

Modules

  • 把Store划分成若干个 Module,避免臃肿

  • 每个Module有自己的State、Mutation、Action、Getter等

  • 二合一的state
    const moduleA = {
    state: { ... },
    mutations: { ... },
    actions: { ... },
    getters: { ... }
    }

    const moduleB = {
      state: { ... },
      mutations: { ... },
      actions: { ... }
    }
    
    const store = new Vuex.Store({  // 包含2个子module
      modules: {
        a: moduleA,
        b: moduleB
      }
    })
    
    store.state.a // -> moduleA's state
    store.state.b // -> moduleB's state
    
  • 本地State

    • Module里的Getter等拿到的是Module自己的State,
    • 如果要访问根State,在Action里要使用context.rootState,而在Getter里rootState作为第三个参数传入。
  • 名字空间

    • 默认情况下不同Module里的Mutation等都注册在全局名字空间

    • 可以使用前缀或者后缀来区分

    • 样例
      // types.js

      // 定义名字常量并添加前缀
      export const DONE_COUNT = 'todos/DONE_COUNT'
      export const FETCH_ALL = 'todos/FETCH_ALL'
      export const TOGGLE_DONE = 'todos/TOGGLE_DONE'
      
      // modules/todos.js
      import * as types from '../types'
      
      // define getters, actions and mutations using prefixed names
      const todosModule = {
        state: { todos: [] },
      
        getters: {
          [types.DONE_COUNT] (state) {
            // ...
          }
        },
      
        actions: {
          [types.FETCH_ALL] (context, payload) {
            // ...
          }
        },
      
        mutations: {
          [types.TOGGLE_DONE] (state, payload) {
            // ...
          }
        }
      }
      
  • 注册Module
    store.registerModule('myModule', {
    // ...
    })

    // 调用
    store.state.myModule.
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,175评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,674评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,151评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,597评论 1 269
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,505评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,969评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,455评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,118评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,227评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,213评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,214评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,928评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,512评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,616评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,848评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,228评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,772评论 2 339

推荐阅读更多精彩内容

  • Vuex 是什么? ** 官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式**。它采用集中...
    Rz______阅读 2,294评论 1 10
  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 2,923评论 0 7
  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 3,096评论 0 6
  • Vuex 的学习记录 资料参考网址Vuex中文官网Vuex项目结构示例 -- 购物车Vuex 通俗版教程Nuxt....
    流云012阅读 1,447评论 0 7
  • vuex是什么鬼? 如果你用过redux就能很快的理解vuex是个什么鬼东西了。他是vuejs用来管理状态的插件。...
    麦子_FE阅读 6,847评论 3 37