Vuex使用

从别处搬的代码用久了,一直不知道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
    既然mutations是处理同步的,那我们自然需要一个能处理异步事件的函数,这时候actions就登场了,actions和mutations的调用方法大同小异,官方文档都有介绍

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

actions接收的context是与store具有相同属性及方法的实例,但不等同于store;
因此在actions中:

	 - 可以通过context.getters来获取state中的属性,不可以直接state.count,而需要context.getters("count"),前提是提供了count的getter方法
	 - 可以直接context.commit一个mutation,如context.commit('increment')

也可以通过结构简写成

	actions: {
		increment ({commit, getters}) {
   	getters("count")
    	 commit('increment')
   	}
	 }

这样就不需要每次调用都用context.xxx了
当异步函数actions处理完成之后,我们怎么拿到函数处理结束的结果呢?
actions是异步函数,它返回的是一个promise,所以我们可以在.then里面处理返回结果:

...mapActions(["increment "])
this.increment().then(()=>{
	//异步函数返回结果处理
})

还可以actions调用actions

actions: {
 actionB ({ dispatch, commit }) {
   return dispatch('actionA').then(() => {
     commit('someOtherMutation')
   })
 }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值