vuex的学习

本文学习自jspang的博客和b站视频 首页 | 技术胖-胜洪宇关注web前端技术-前端免费视频第一博客

一.state里写data数据和prop属性

store写法

const state={
    count:1
}

html写法

先在script里引入store文件

1.渲染store 的state里的数据

<div> {{$store.state.count}} </div>

通过三种方式将html的写法改变成下面这种 

<div> {{count}} </div>

one

computed:mapState({
        count:state=>state.count
 })

 two

 computed:mapState(["count"])

there

...mapstate(["count"])

二.mutation里写改变(状态)数据的方法

store写法

const mutations={
    add(state){
        state.count++;
    },
    reduce(state){
        state.count--;
    }
}

HTML写法

调用store的mutation里的方法

commit即提交什么方法的意思

<button @click="$store.commit('add')">+</button>

在mutation传递参数并在html渲染

store

const mutations={
    add(state,n){
        state.count+=n;
    },
    reduce(state){
        state.count--;
    }
}

html

<p>
   <button @click="$store.commit('add',10)">+</button>
   <button @click="$store.commit('reduce')">-</button>
</p>

 将上面的方法转换成下面的这种写法,即去除$store.commit

<button @click="reduce">-</button>

方法

 methods:mapMutations([
        'add','reduce'
]),

三.getters计算过滤操作 (相当于html页面的compute)

store写法 

const getters = {
    count:function(state){
        return state.count +=10;
    }
}

 在html用getters里的方法

computed:{
    ...mapState(["count"]),
    ...mapGetters(["count"])
},

四.actions异步修改状态 

 store写法

const actions ={
    addAction(context){
        context.commit('add',10)
    },
    reduceAction({commit}){
        commit('reduce')
    }
}

HTML写法

<p>
  <button @click="addAction">+</button>
  <button @click="reduceAction">-</button>
</p>
methods:{
    ...mapMutations([  
        'add','reduce'
    ]),
    ...mapActions(['addAction','reduceAction'])
},

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值