美文网首页
Vuex的使用

Vuex的使用

作者: 格子GiMi | 来源:发表于2018-11-21 15:02 被阅读0次

从别处搬的代码用久了,一直不知道Vuex具体是为了干什么的,该怎么去用它。

  • Vuex是什么
    vuex的核心是一个store(仓库),包含着应用中需要用到的state(状态)。

  • 什么情况下使用Vuex

    为了在多个视图引用同一个 “变量 ” ,并且无论在哪个视图中对这个 “变量 ” 进行修改,其他视图中都能同步这个修改, 我们可以将这个 “变量 ” 放入store的state中

  • 如何使用Vuex【同步状态state】

    假如,我们需要在多个视图中使用同一个变量 count,先在store(仓库)中添加一个state(状态)名为 count :

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

    如今我们想修改count的值,虽然可以直接使用 store.state.count = 5 ;但是这样无法实现同步,vuex中提供了mutations方法,需要使用 state.commit('increment ') 来触发 mutations 来改变 count的值。还可以用commit方法传参来更灵活的修改count的值:

    mutaion: {
        increment (state, n) {
            state.count += n;
        }
    }
    
    store.commit('increment', 10);
    

    单单传一个参数可能很难满足我们开发的需求,这时可以传入一个payload(提交载荷):

    mutation: {
        increment (state, payload) {
            state.totalPrice += payload.price + payload.count;
        }
    }
    
    store.commit({
        type: 'increment',
        price: 10,
        count: 8
    })
    

    为了触发所有的视图同步更新count的功能,我们将count的值放入计算属性 computed中:

    computed: {
            count () {
                return this.$store.state.count
            }
        }
    

    使用这种方法看起来很冗余,vuex提供了mapState辅助函数,我们可以通过这样使用,以简化编码:

    computed: mapState([ 'count' ])
    

    这样便可以将 this.count 映射为 store.state.count;

  • Getters对象

    虽然我们同步更新了这个状态,但往往会需要再对这个参数进行处理之后才能使用,当然,我们可以在每一处引用的地方添加一个处理函数,但是,当这个处理过程需要更改时,我们需要在所有引用的地方复制一遍 新的处理函数,很没有效率,不便于维护。

    Vuex中getters对象,可以方便我们在store中做集中的处理。Getters接受state作为第一个参数:

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

    组件中调用形式:

    computed: {
      doneTodos () {
        return this.$store.getters.doneTodos
      }
    }
    

    同理,这样调用比较繁琐,vuex提供了一个和mapState 作用相同的辅助函数 mapGetters,在计算属性中这样引入:

    computed: mapGetters([
          'doneTodosCount',
          'anotherGetter',
          // ...
        ])
    
  • 同步函数mutations
    mutations是改变state的唯一方法,我们在项目中需要改变state的值时,使用 state.commit('increment') ,不如直接使用methods那么方便,vuex提供了mapMutations映射函数,使我们在调用methods时可以映射为 state.commit调用:

    // 注 Mutations必须是同步函数。
    methods: {
        ...mapMutations([
          'increment' // 映射 this.increment() 为 this.$store.commit('increment')
        ]),
        ...mapMutations({
          add: 'increment' // 映射 this.add() 为 this.$store.commit('increment')
        })
      }
    
  • 异步函数Aciton
    妈耶,看不懂,我再去学学..........

相关文章

网友评论

      本文标题:Vuex的使用

      本文链接:https://www.haomeiwen.com/subject/oalcqqtx.html