Vuex状态管理器

创建vuex对象:

 注册vuex对象实例到main.js

 使用状态管理器:

  • state属性

作用:用来定义一系列共享数据

// 创建store对象
const store = new Vuex.Store({
    state:{  // 用来定义共享数据  组件中使用共享数据:this.$store.state.counter ==>简化写法($store.state.counter)
        counter:12,
    }
});


// 组件中使用共享数据
<h1>{{msg}}登录系统=={{this.$store.state.counter}}</h1>  
//<h1>{{msg}}登录系统=={{$store.state.counter}}</h1>  // 简化写法
  • mutations属性

作用:用来定义对共享数据修改方法‘

// 创建store对象
const store = new Vuex.Store({
    state:{  // 用来定义共享数据  组件中使用共享数据:this.$store.state.counter ==>简化写法($store.state.counter)
        counter:12,
    },
    mutations:{  // 用来定义对共享数据修改方法,这里面定义方法都有一个默认参数,默认参数会将状态对象传递给自定义方法  组件中调用这个方法:this.$store.commit('方法名')
        addCounter(state){   // 自定义方法
            state.counter += 10   
        }
    }
});

// 组件中使用共享数据
<button @click="addcout">点击+10</button>

  methods: {
    addcout(){
      this.$store.commit('addCounter')  // 调用共享管理器中的方法
    }
  },

方法传参:属性或对象

// 创建store对象
const store = new Vuex.Store({
    state:{  // 用来定义共享数据  组件中使用共享数据:this.$store.state.counter ==>简化写法($store.state.counter)
        counter:12,
    },
    mutations:{  // 用来定义对共享数据修改方法,这里面定义方法都有一个默认参数,默认参数会将状态对象传递给自定义方法  组件中调用这个方法:this.$store.commit('方法名')
        addCounter(state, aa){   // 自定义方法
            state.counter += aa   // 如果是个对象:aa.key即可 
        }
    }
});

// 组件中使用共享数据
<button @click="addcout">点击+10</button>

  data:{
    aa:10
  }
  methods: {
    addcout(){
      this.$store.commit('addCounter', this.aa)  // 调用共享管理器中的方法
      //this.$store.commit('addCounter', {aa:12, bb:22})  // 参数是个对象
    }
  },
  • getters属性

作用:用来书写对共享数据进行计算方法 相当于组件中computed,好处:只计算一次

// 创建store对象
const store = new Vuex.Store({
    state:{  // 用来定义共享数据  组件中使用共享数据:this.$store.state.counter ==>简化写法($store.state.counter)
        counter:12,
    },
    mutations:{  // 用来定义对共享数据修改方法,这里面定义方法都有一个默认参数,默认参数会将状态对象传递给自定义方法  组件中调用这个方法:this.$store.commit('方法名')
        addCounter(state, aa){   // 自定义方法
            state.counter += aa
        }
    },
    getters:{  // 用来定义共享数据的一系列方法:好处只计算一次,缓存结果  组件中使用getters定义的计算属性:this.$store.getters.counterSqrt
        counterSqrt(state){  // 这里面定义方法都有一个默认参数,默认参数会将状态对象传递给自定义方法
            return state.counter*state.counter  // 求平方
        }
    }
});


// 组件中使用getters中的计算属性
<h1>欢迎{{ msg }}登录员工管理系统==={{$store.state.counter}}--{{this.$store.getters.counterSqrt}}</h1>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值