vuex的使用

vuex

https://www.jianshu.com/p/a804606ad8e9

1.安装

npm install vuex --save

2.导入

import Vuex from 'vuex'
Vue.use(Vuex)

3.创建库

var store = new Vuex.Store({
    state:{
        count:0
    },
    mutations:{
        increment(state){
            state.count++;
        },
        remove(state,obj) {
          state.count -= (obj.a + obj.b)
        }
    },
    getters: {
        optCount:(state => {
            return '当前值:'+ state.count;
        })
    }

})

4.挂载

var vm = new Vue({
    el:'#app',
    render:function (c) {
      return   c(app)
    },
    router,
    store
})

5.使用

<template>
  <div>
    <input type="button" value="减少" @click="remove">
    <input type="button" value="增加" @click="add">
    <br>
    <input type="text" v-model="$store.state.count">
    <h3>{{$store.getters.optCount}}</h3>
  </div>
</template>

<script>
    export default {
        data() {
            return {
            };
        },
        methods: {
            add(){
                this.$store.commit('increment')
            },
            remove(){
                this.$store.commit('remove',{a:1,b:2})
            }
        }
    };
</script>

<style scoped>

</style>

new Vuex.Store() 实例,得到一个 数据仓储对象
var store = new Vuex.Store({
state: {
// 大家可以把 state 想象成 组件中的 data ,专门用来存储数据的
// 如果在 组件中,想要访问,store 中的数据,只能通过 this.KaTeX parse error: Expected 'EOF', got '}' at position 36: … count: 0 }̲, mutations: …store.commit(‘方法名’)
// 这种 调用 mutations 方法的格式,和 this.$emit(‘父组件中方法名’)
subtract(state, obj) {
// 注意: mutations 的 函数参数列表中,最多支持两个参数,其中,参数1: 是 state 状态; 参数2: 通过 commit 提交过来的参数;
console.log(obj)
state.count -= (obj.c + obj.d)
}
},
getters: {
// 注意:这里的 getters, 只负责 对外提供数据,不负责 修改数据,如果想要修改 state 中的数据,请 去找 mutations
optCount: function (state) {
return ‘当前最新的count值是:’ + state.count
}
// 经过咱们回顾对比,发现 getters 中的方法, 和组件中的过滤器比较类似,因为 过滤器和 getters 都没有修改原数据, 都是把原数据做了一层包装,提供给了 调用者;
// 其次, getters 也和 computed 比较像, 只要 state 中的数据发生变化了,那么,如果 getters 正好也引用了这个数据,那么 就会立即触发 getters 的重新求值;
}
})

总结:

  1. state中的数据,不能直接修改,如果想要修改,必须通过 mutations
  2. 如果组件想要直接 从 state 上获取数据: 需要 this.$store.state.****
  3. 如果 组件,想要修改数据,必须使用 mutations 提供的方法,需要通过 this.$store.commit(‘方法的名称’, 唯一的一个参数)
  4. 如果 store 中 state 上的数据, 在对外提供的时候,需要做一层包装,那么 ,推荐使用 getters, 如果需要使用 getters ,则用 this.$store.getters.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值