zoukankan      html  css  js  c++  java
  • vuex的应用和解决的实际问题

    这是vuex的语法结构内容

    简单的理解vuex:
    new Vue({
      // state
      data () {
        return {
          count: 0
        }
      },
      // view
      template: `
        <div>{{ count }}</div>
      `,
      // actions
      methods: {
        increment () {
          this.count++
        }
      }
    })
    state,驱动应用的数据源;(单向数据流)
    view,以声明方式将 state 映射到视图;(静态显示出来的数据源)
    actions,响应在 view 上的用户输入导致的状态变化 (数据源变化追踪)
    ---------------------------------------------------------------------------------
    vuxe解决了:
    1.多个组件共享状态时,单向数据流的简洁性很容易被破坏:
    2.多个视图依赖于同一状态。
    3.来自不同视图的行为需要变更同一状态。
    ---------------------------------------------------------------------------------
    vuex使用场景:
    中大型单页应用,考虑如何更好地在组件外部管理状态,简单应用不建议使用。
    ---------------------------------------------------------------------------------
    Vuex 的状态存储是响应式的
    state:
    从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态
    如:
    view层:
    template: `
        <div>{{ count }}</div>
      `
    computed: {
        count () {
          return store.state.count
        }
      }
    (这种方式频繁操作的话繁琐于是有了更好的解决方式,因为在每个需要使用 state 的组件中都需要频繁地导入)
    Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex))
    通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到
    computed: {
        count () {
          return this.$store.state.count
        }
      }
    (这种方式比较好)
    -----------------------------------------------------------------------------------
    当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。此时可以用使用 mapState 辅助函数帮助我们生成计算属性(少写好多代码的)
    import { mapState } from 'vuex'
    export default {
      computed: mapState({
        // ES6箭头函数可使代码更简练
        count: state => state.count,
        
        countAlias: 'count',  //传字符串参数'count'等同于`state => state.count`
        
        countPlusLocalState (state) {
          return state.count + this.localCount // 为了能够使用`this`获取局部状态,必须使用常规函数
        }
      })
    }
    
    当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
    computed: mapState([ 
      'count'//映射 this.count为store.state.count
    ])
    
    对象展开运算符(简单的mapState可以传数组和对象对象时候前面的属性是自定义的别名)
    computed: {
      localComputed () { /* ... */ },
      ...mapState({  // 使用对象展开运算符将此对象混入到外部对象中
    
      })
    }
    -----------------------------------------------------------------------------------
    同state,vuex里面的getter也是如此:
    computed: {
      doneTodosCount () {
        return this.$store.state.todos.filter(todo => todo.done).length //对数据源进行基本的操作
      }
    }
    (最初始是如果有多个组件需要用到此属性,我们要么复制这个函数,或者抽取到一个共享函数然后在多处导入它)
    进而:
    Vuex允许我们在store中定义“getter”可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
    mapGetters 辅助函数
    mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:
    import { mapGetters } from 'vuex'
    export default {
      computed: {
        ...mapGetters([  //使用对象展开运算符将getter混入computed对象中
          'doneTodosCount',(实际就是导出一个方法,可以获取里面的东西和一些操作)
          'anotherGetter',
          // ...
        ])
      }
    }
    如果你想将一个getter属性另取一个名字,使用对象形式:
    mapGetters({
      doneCount: 'doneTodosCount' //映射`this.doneCount`为`store.getters.doneTodosCount`
    })
    -----------------------------------------------------------------------------------
    更改 Vuex 的 store 中的状态的唯一方法是提交 mutation:
    Vuex中的mutation非常类似于事件:每个mutation都有一个字符串的 事件类型 (type)和一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
    const store = new Vuex.Store({
      state: {
        count: 1
      },
      mutations: {
        increment (state) {
          // 变更状态
          state.count++
        }
      }
    })
    (最初始是这样的,但是注意一定是同步操作,异步是不行的)
    你不能直接调用一个 mutation的回调,需要store.commit('increment')
    向store.commit传入额外的参数,叫做mutation的 载荷(payload)
    mutations: {
      increment (state, n) {
        state.count += n
      }
    }
    store.commit('increment', 10)
    
    在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:
    mutations: {
      increment (state, payload) {
        state.count += payload.amount
      }
    }
    store.commit('increment', {
      amount: 10
    })
    (传进去的是什么,调用的是时候也是传对应的值就好了)
    提交的另外一种方式:对象风格的提交方式(此时回调是不变的)
    store.commit({
      type: 'increment',
      amount: 10
    })
    Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项:
    1.最好提前在你的 store 中初始化好所有所需属性。
    2.当需要在对象上添加新属性时,你应该使用 Vue.set(obj, 'newProp', 123), 或者
    以新对象替换老对象:state.obj = { ...state.obj, newProp: 123 }
    一般会独立开来(使用mutation-types.js存放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
        }
      }
    })
    你可以在组件中使用this.$store.commit('xxx')提交 mutation或者使用 mapMutations 辅助函数(需要在根节点注入 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 类似于 mutation,不同在于:
    1.Action 提交的是 mutation,而不是直接变更状态。
    2.Action 可以包含任意异步操作。
    简单的:
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment (state) {
          state.count++
        }
      },
      actions: {
        increment (context) {
          context.commit('increment')
        }
      }
    })
    Action 函数接受一个与 store 实例具有相同方法和属性的context(函数上下文)对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。
    context对象并不是store实例本身
    提交:
    actions: {
      increment ({ commit }) {
        commit('increment')
      }
    }
    
    分发(触发)Action:
    store.dispatch('increment')
    
    异步操作:
    actions: {
      incrementAsync ({ commit }) {
        setTimeout(() => {
          commit('increment')
        }, 1000)
      }
    }
    Actions 支持同样的载荷方式和对象方式进行分发:
    //以载荷形式分发
    store.dispatch('incrementAsync', {
      amount: 10
    })
    
    //以对象形式分发
    store.dispatch({
      type: 'incrementAsync',
      amount: 10
    })
    
    你在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用mapActions辅助函数
    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:
    实际项目没用过async/await大概理解就是等待执行完上一个方法后(结束后)再走下一步(下一个方法)
    // 假设 getData() 和 getOtherData() 返回的是 Promise
    actions: {
      async actionA ({ commit }) {
        commit('gotData', await getData())
      },
      async actionB ({ dispatch, commit }) {
        await dispatch('actionA') // 等待 actionA 完成
        commit('gotOtherData', await getOtherData())
      }
    }
    -----------------------------------------------------------------------------------
    Module(Vuex 允许我们将 store 分割成模块(module)解决store 对象臃肿)
    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 的状态
    (简单认为符合上面的组织形式的成为单独模块)(项目不足够大不建议使用)

  • 相关阅读:
    Python基础综合练习
    熟悉常用的Linux操作
    大数据概述
    C语言简易文法(无左递归)
    自动机
    C语言简易文法
    词法分析实验报告
    词法分析
    综合练习:词频统计
    组合数据类型综合练习
  • 原文地址:https://www.cnblogs.com/lhl66/p/8302575.html
Copyright © 2011-2022 走看看