218、VUEX

 
 
注意:前端单页面应用,就是把状态和路由连起来
import Vue from 'vue'
import router from './router'
import store from './store'
import '@/permission'//router.beforeEach
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
mutation:突变,改变
注意:从定义和使用两个方面来理解VUEX
一、VUEX简介
1、redux 处理同步用 dispatch action(对象类型),处理异步用 dispatch action(函数类型)
2、Vuex 处理同步用 commit mutations ,处理异步用 dispatch action commit mutations
3、Vuex 的 Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象

二、模块(默认)
注意:Vuex允许我们将 store 分割成 module,每个模块拥有自己的 state、mutation、action、getter、module。
1、mutation 的第一个参数是局部状态对象。
2、action 会收到 局部参数 和 rootState。
3、getter 会收到 state、getters 和 rootState。
4、mutation、action 和 getter 是(通过递归)注册在全局命名空间的。
5、在模块里,通过 commit(mutation) 或者 dispatch(action)执行。

三、模块(命名空间)
注意:添加 namespaced: true 的方式使其成为带命名空间的模块。mutation、action 和 getter 会自动调整命名。
1、mutation 的第一个参数是局部状态对象。
2、action 会收到 局部参数 和 rootState、rootGetters。
3、getter 会收到 state、getters 和 rootState、rootGetters 4个参数。
4、mutation、action 和 getter 是注册在局部命名空间的。
5、在模块里,通过 commit(mutation)、dispatch(action) 或者 commit('someAction', null, { root: true })、dispatch('someAction', null, { root: true })执行。通过给 action 添加 root: true 和 handler ,就可以在本命名空间注册全局 action ,在全局命名空间 dispatch 。

四、this.$store与store的区别
1、在".vue"组件里,通过 this.$store.commit(mutation) 或者 this.$store.dispatch(action) 执行。
2、在"store.js"文件里,可以通过 { getter: { count: (state, getters) => { /* return getters.count.length */ } } }执行。
2、在其它".js"文件里,可以通过 store.commit(mutation) 或者 store.dispatch(action) 执行。

五、Vuex
1、Vuex实例配置:
(1)state
(2)mutations(state)//在store上注册mutation,处理函数总是接受state作为第一个参数
(3)actions(context)//与store实例具有相同方法和属性的context对象
(4)getters(state,getters)
(5)modules
(6)plugins
(7)strict
(8)devtools
2、实例获取:new Vuex.Store({})
3、实例的属性和方法
(1)实例属性:state、getters
(2)实例方法:commit、dispatch、replaceState、watch、subscribe、subscribeAction、registerModule、unregisterModule、hotUpdate
(3)供给组件的辅助函数:mapState、mapGetters、mapActions、mapMutations、createNamespacedHelpers,通过import { XXX } from 'vuex'

4、store 实例
const store = new Vuex.Store({
  state: {
    count: 0,
    todos: [
      { id: 1, text: '11111', done: true },
      { id: 2, text: '11111', done: true },
      { id: 3, text: '11111', done: false }
    ]
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    }
  },
  actions: {
    Login({commit}, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password, userInfo.code).then(response => {
          commit('SET_TOKEN', '5663DC3C8A12FFD684E9A8FC29984212')
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    }
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    },
    doneTodosCount: (state, getters) => {  
      //return getters.doneTodos.length 
    },
    getTodoById: (state) => (id) => {
      //store.getters.getTodoById(2) 或 this.$store.getters.getTodoById(2)
      return state.todos.find(todo => todo.id === id)
    }
  },
  modules: {
    app,
    user,
    permission
  }
})
const store = new Vuex.Store({
  modules: {
    app,
    user,
    permission
  },
  getters
})

5、mapState:将store中的state映射到局部计算属性:
<p>
  mapState方式 {{count}}
</p>
computed: {
  ...mapState([
    'count'//映射this.count为store.state.count。当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
  ]),
}
//上面将 mapState 的每一项作为 computed 对象的每一项,
//下面用 mapState 的整体来取代 computed 对象的整体,
computed: mapState({
  count: state => state.count,// 箭头函数可使代码更简练
  countAlias: 'count',// 传字符串参数 'count' 等同于 `state => state.count`
  countPlusLocalState (state) {
    return state.count + this.localCount// 为了能够使用 `this` 获取局部状态,必须使用常规函数
  }
})

6、mapMutations:将组件中的 methods 映射为 store.commit 调用,代替使用 this.$store.commit('xxx') 提交 mutation,
export default {
  methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
      'incrementBy' // `mapMutations` 也支持载荷:将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}

7、mapActions:将组件中的 methods 映射为 store.dispatch 调用,代替使用 this.$store.dispatch('xxx') 分发 action,
export default {
  methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
      'incrementBy' // `mapActions` 也支持载荷:将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}

8、mapGetters:将store中的getter映射到局部计算属性
<template>
  <div>
    <h4>测试1:Count is {{ count }}</h4>
    <P>通过属性访问:{{ doneTodosCount }}</p>
    <P>通过方法访问:{{ doneTodos }}</p>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
  computed:{
    count(){
      return this.$store.state.count
    },
    ...mapGetters([// 使用对象展开运算符将 getter 混入 computed 对象中
      'doneTodos',
      'doneTodosCount'
    ]),
    ...mapGetters({// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
      doneCount: 'doneTodosCount'
    })
  }
}
</script>

猜你喜欢

转载自www.cnblogs.com/gushixianqiancheng/p/13390690.html