vuex学习笔记

一、vuex的作用

    提供一个在多个组件间共享状态的插件。需要共享状态的有用户登录状态、用户名称、头像、地理位置信息等等。


二、使用步骤

    1.在src文件中创建一个文件夹store,并且在其中创建一个index.js文件

在index.js中写入以下代码:

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

Vue.use(Vuex)

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

export default store



   2.在main.js文件,导入store对象,并放在new Vue中

代码如下(示例):

import store from './store/index'

new Vue({
    el: "#app",
    router,
    store,
    render: h => h(App)
});

    3.具体使用

this.$store.state.变量名 //访问状态 
this.$store.commit(mutation中的方法)//修改状态

三、vuex核心概念

     1.state

如果状态信息是保存到多个 Store 对象中的,那么之后的管理和维护等等都会变得特别困难。所以 单一状态树用来管理应用层级的全部状态。(即共享状态信息)

     2.getters 

              从store中获取一些state变异后的状态,getters默认是不能传递参数的,如果希望传递参                数,那么只能让getters本身返回另一个函数。

//从下面的store中获取学生年龄大于20的个数
const store = new Vuex.Store({
    state: {
        students: [
            { id: 110, name: 'why', age: 18 },
            { id: 111, name: 'why1', age: 19 },
            { id: 112, name: 'why2', age: 16 },
        ]
    },
    getters: {
        getAgeCount: state => {
            return state.students.filter(s => s.age >= 20).length
        }
    }
//传递参数,根据ID获取用户信息
getters: {
        stuById: state => {
            return id => {
                return state.students.find(s => s.id === id)
            }
        }
    }

      3.mutation

             提交mutation是store状态更新的唯一方式,通过mutation更新的数据携带的参数被成为载               荷(Payload)

mutations: {
  increment(state, n){
    state.count += n;
  }
}//mutation的定义方式
store.commit('increment', 10);//通过mutation更新

             当有很多参数需要传递时,以对象形式

mutations: {
  increment(state, payload)
  state.count += payload.amount;
}
}
store.commit('increment', {amount: 10});

       4.action

              类似于mutation,用来代替mutation进行异步操作

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

     5.module

             Vuex允许我们将store分割成模块(Module), 而每个模块拥有自己的state、                                       mutationsactionsgetters

const moduleA = {
  state: { count: 0},
  getters: {
    doubleCount(state){
      return state.count * 2;
    }
  },
  mutations: {
    increment(state){
      state.count ++ ;
    }
  },
 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值