vue-vuex

事件总线

Vue.prototype.bus = new Vue()
console.log(this.bus)
子组件 this.bus.$emit()
父组件 created(){this.bus.$on()}

vuex

npm install vuex --D2.x版本
vue add vuex 3.x版本

state 公共数据池

在computed接收 this.$store.state.xxx

mapState 返回值是个对象
computed:mapState(['name','age','look'])

data优先级高于computed里的
更改命名方式避免冲突

computed:mapState({
  storeName: state=>state.age,
})
computed:{
  ...mapState({
    storeName: state=>state.age,
  }),//拿到值
  a(){
    return 111
  }//定义自己的计算属性
  ...mapGetters({
    student:'newStudent'
  })
  // newStudent(){
  //   return this.$store.getters.newStudent
  // }
  
},
methods:{
  // add(){
  //   //this.$store.commit()
  //   dispatch//派发异步
  // }
  ..mapActions({})
}
//store.js里的computed计算属性
getters:{
  newStudent(state,getters){
    console.log(getters.a)
    
  },
  a(){
    return 111
  }//定义自己的计算属性
  

}
//更改数据池里的数据
mutations:{
  changeStudent(state,{name,number}){

  }
  
}
//存放异步操作
actions:{


}

strict:true

vuex module

const 模块名={
  namespace:true
  .....
}
.....
modules:{
  模块名
}

引用
('模块名',{....})
模块名/xxx
createNamespacedHelpers

vuex官方文档

安装

引入

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

浏览器不支持Promise
引入

或者
npm install es6-promise --save # npm
yarn add es6-promise # Yarn
import 'es6-promise/auto'

Vuex 是什么?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

  • state,驱动应用的数据源;
  • view,以声明方式将 state 映射到视图;
  • actions,响应在 view 上的用户输入导致的状态变化。

多个组件共享状态时,单向数据流的简洁性很容易被破坏:

  • 多个视图依赖于同一状态。
  • 来自不同视图的行为需要变更同一状态。

最简单的 Store

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

  1. Vuex 的状态存储是响应式的。
  2. 你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。方便跟踪

单一状态树 State

  1. 唯一数据源
  2. 单状态树和模块化并不冲突

从 store 实例中读取状态:在计算属性中返回某个状态。需要频繁导入。

// 创建一个 Counter 组件
const Counter = {
  template: `
{{ count }}
`, computed: { count () { return store.state.count } } }

Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中”: 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件

const app = new Vue({
  el: '#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Counter },
  template: `
    
` }) //根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。 const Counter = { template: `
{{ count }}
`, computed: { count () { return this.$store.state.count } } }

mapState 辅助函数帮助我们生成计算属性,让你少按几次键:

computed: mapState({
   // 箭头函数可使代码更简练
   count: state => state.count,

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

   // 为了能够使用 `this` 获取局部状态,必须使用常规函数
   countPlusLocalState (state) {
     return state.count + this.localCount
   }
 })


//当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
computed: mapState([
 // 映射 this.count 为 store.state.count
 'count'
])



//mapState 函数返回的是一个对象。我们如何将它与局部计算属性混合使用:对象展开运算符
computed: {
 localComputed () { /* ... */ },
 // 使用对象展开运算符将此对象混入到外部对象中
 ...mapState({
   // ...
 })
}


 

Getter

有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数。
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)
    },
    //两个参数
    doneTodosCount: (state, getters) => {
      return getters.doneTodos.length
    }
  }
})

//我们可以很容易地在任何组件中使用它:
computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}

通过方法访问

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

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


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

mapGetters 辅助函数

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    //数组形式
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])

    //对象形式
    ...mapGetters({
      // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
      doneCount: 'doneTodosCount'
    })


    
  }
}

Mutation

基本使用

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

// store.commit 传入额外的参数,即 mutation 的 载荷(payload):
// ...
mutations: {
  increment (state, n) {
    state.count += n
  }
}



//”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法:
store.commit('increment', 10)

对象形式的载荷

// ...
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}

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

对象风格的提交方式

//直接使用包含 type 属性的对象
store.commit({
  type: 'increment',
  amount: 10
})

Mutation 需遵守 Vue 的响应规则

  1. 最好提前在你的 store 中初始化好所有所需属性。
  2. 当需要在对象上添加新属性时,你应该
  • 使用 Vue.set(obj, 'newProp', 123), 或者
  • 以新对象替换老对象。例如,利用 stage-3 的对象展开运算符我们可以这样写:state.obj = { ...state.obj, newProp: 123 }

使用常量替代 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
    }
  }
})

Mutation 必须是同步函数

因为当 mutation 触发的时候,回调函数还没有被调用,devtools 不知道什么时候回调函数实际上被调用——实质上任何在回调函数中进行的状态的改变都是不可追踪的。

在组件中提交 Mutation

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

异步

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

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

当我们在之后介绍到 Modules 时,你就知道 context 对象为什么不是 store 实例本身了。

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

实践中,我们会经常用到 ES2015 的 参数解构 来简化代码(特别是我们需要调用 commit 很多次的时候):

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

分发 Action

Action 通过 store.dispatch 方法触发:
store.dispatch('increment')

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

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

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

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

//注意我们正在进行一系列的异步操作,并且通过提交 mutation 来记录 action 产生的副作用(即状态变更)。
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)
    )
  }
}

在组件中分发 Action

  1. this.$store.dispatch('xxx') 分发 action(需要先在根节点注入 store)。
  2. 使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用:
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: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}
store.dispatch('actionA').then(() => {
  // ...
})

在另外一个 action 中也可以:

actions: {
  // ...
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

利用 async / await,我们可以如下组合 action

// 假设 getData() 和 getOtherData() 返回的是 Promise

actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}

一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。

Module

将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、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 的状态
  • 模块的局部状态对象,局部状态通过 context.state暴露出来
  • 根节点状态则为context.rootState
const moduleA = {
  state: { count: 0 },

  getters: {
    sumWithRootCount (state, getters, rootState) {
      return state.count + rootState.count
    }
  }
  mutations: {
    increment (state) {
      // 这里的 `state` 对象是模块的局部状态
      state.count++
    }
  },

  getters: {
    doubleCount (state) {
      return state.count * 2
    }
  },

  actions: {
    incrementIfOddOnRootSum ({ state, commit, rootState }) {
      if ((state.count + rootState.count) % 2 === 1) {
        commit('increment')
      }
    }
  }
}

命名空间

通过添加 namespaced: true 的方式使其成为带命名空间的模块:具有更高的封装度和复用性

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

启用了命名空间的 getter 和 action 会收到局部化的 getter,dispatch 和 commit。换言之,你在使用模块内容(module assets)时不需要在同一模块内额外添加空间名前缀。更改 namespaced 属性后不需要修改模块内的代码。

你可能感兴趣的:(vue-vuex)