vueX

vuex

State:定义了应用状态的数据结构,可以在这里设置默认的初始状态。 类似于data
Getter:允许组件从 Store 中获取数据,mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性。 类似于computed
Mutation:是唯一更改 store 中状态的方法,且必须是同步函数。 类似于methods
Action:用于提交 mutation,而不是直接变更状态,可以包含任意异步操作。 异步是dispatch
Module:可以将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割

 1.   State
      const store=new  Vuex.Store({
          state:{
          count:5
          }
      })
 2. getters
     const store =new Vuex.Store({
     state:{
     count:5
     },
     getters:{
       newCount:state=> state.count*5    //箭头函数   不加花括号直接return
    }
     })

 在组件中获取方式----newCount
    export default {
      computed:{
        newCount(){
          return this.$store.getters.newCount
        }
      }
    }
 3. Mutation
     我们在 mutations中定义了一个叫increment的函数,函数体就是我们要进行更改的地方
会接受 state作为第一个参数,第二个是自定义传参
  const store=new  Vuex.Store({
          state:{
            count:5
          },
          mutations:{
            increment(state,value){
            state.count += value;
               }
          }
      })
      我们在提交commit时候,字符串参数increment,就是对应在 mutations中的increment
      export default ({
          methods:{
            get(){
            this.$store.commit('increment',3)
            }     
          }
    })
4.Action
     用于提交 mutation,而不是直接变更状态,可以包含任意异步操作。
     只有通过action=>mutations=>states,这个流程进行操作,具体步骤如下:  
        const store=new  Vuex.Store({
          state:{
            count:5
          },
          mutations:{
            increment(state,value){
            state.count += value;
               },
          },
          action:{
          //第一个参数为store,可以任意起名,若{commit},变量解构--  commit=store.commit
              getAsync(store){
          //action 函数接收一个 store 的实例对象,因此你可以调用 store.commit 提交mutation
                 store.commit('increment',10)
              }
          }
      })

		//组件里使用
		   methods:{
		   getAsync(){
		         this.$store.dispacth('getAsync')
		     }
		     //还可以使用数组解构  methods的函数名和mutation函数名一样
		     ...mapActions(['getAsync'])
		   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值