数据仓库vuex的使用方法

 VUEX的一般结构如下:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
var store = new Vuex.Store({
  state: {
    // 相当于data
  },
  mutations: {
    // 相当于methods
  },
  getters: {
    //相当于filter
  }
})
import App from './App.vue'
const vm = new Vue({
  el: '#app',
  render: c => c(App),
  store // 将 vuex 创建的 store 挂载到 VM 实例上
})

使用VUEX实现下面的功能:

步骤:

1、在store中定义一个count 来记录输入框中的数值

state: {
    count: 0
},

2、第一个子组件通过 this.$store.state.count 来访问这个数据

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

3、第一个组件实现增加+和减少-操作,

注意: 如果要操作 store 中的 state 值,只能通过调用 mutations 提供的方法,才能操作对应的数据,不推荐直接操作 state 中的数据,因为万一导致了数据的紊乱,不能快速定位到错误的原因,因为,每个组件都可能有操作数据的方法。

在store mutations 中进行+\-操作方法:

mutations: {
    increment(state) {
      state.count++
    },
    subtract(state, obj) {
      // 注意: mutations 的 函数参数列表中,最多支持两个参数,
      //其中,参数1:是state 状态;参数2:通过 commit 提交过来的参数,可以是对象\数组\其他类型
      state.count -= (obj.c + obj.d)
    }
  },

4、在第一个组件中通过 使用 this.$store.commit('方法名') 调用 mutations 方法,和 this.$emit('父组件中方法名')相似

<template>
  <div class="box">
    <input type="button" value="-" @click="subtract">
    <input type="text" v-model="$store.state.count">
    <input type="button" value="+" @click="add">
  </div>
</template>

<script>
export default {
  methods: {
    add() {
      this.$store.commit("increase");//调用mutation中的+方法
    },
    subtract() {
      this.$store.commit("decrease", { c: 3, d: 1 });//调用mutation中的-方法
    }
  },
};
</script>

<style lang="stylus" scoped>
.box{
  display flex
  input {
    margin 10px
    height 40px
    font-size 18px
  }
  input:not(:nth-child(2)){
    width 50px
    text-align center
  }
}
</style>

5、有时候需要对数据做一层包装, 这时候可以使用store 的 getters,getters 只负责对外提供数据,不负责修改数据,如果想要修改 state 中的数据,请使用 mutations,和filter类似

想在第二个组件中这样显示   '当前最新的count值是:' count值   

 getters: {
    optCount: function (state) {
      return '当前最新的count值是:' + state.count
    }
  }

6、第二个组件中使用store  中包装之后的数据

<template>
  <div>
    <h2>{{ $store.getters.optCount }}</h2>
  </div>
</template>
<script>
</script>
<style lang="stylus" scoped>
</style>

总结:

1、如果组件想要直接从 state 上获取数据: 需要 this.$store.state.属性名

2、state中的数据,不能直接修改,如果想要修改,必须通过 mutations

3、组件通过 this.$store.commit('方法的名称', 唯一的一个参数) 来实现对 store 中 state 数据的操作

4、如果 store 中 state 上的数据, 在对外提供的时候,需要做一层包装,那么 ,推荐使用 getters, 如果需要使用 getters ,则用 this.$store.getters.方法名

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

佛佛ง

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值