Vuex学习笔记

Vuex概述

Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据共享

使用Vuex管理数据的好处:

  • 能够在vuex中集中管理共享的数据,便于开发和后期进行维护
  • 能够高效的实现组件之间的数据共享,提高开发效率
  • 存储在vuex中的数据是响应式的,当数据发生改变时,页面中的数据也会同步更新

Vuex中的核心特性

State

State提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中存储

State使用

在全局main.js中定义:

new Vuex.Store({
  state: {
    count: 0
  }
})

在组件中访问State的方式:

  1. this.$store.state.全局数据名称,如:this.$store.state.count
  2. 按需导入mapState函数:
    import { mapState } from 'vuex'
    
    computed: {
    ...mapState(['count'])//组件中当计算属性使用
    }
    

Mutation

Mutation用于修改变更$store中的数据

Mutation使用

在全局main.js中定义:

new Vuex.Store({
  // 只有mutations才有修改state中数据的权力
  mutations: {
  	// 不带参数
    add (state) {
      // 不要在 mutations函数中,执行异步操作
      // setTimeout(() => {
      //   state.count++
      // }, 1000)
      state.count++
    },
    // 带参数
    addN (state, step) {
      state.count += step
    }
  }
})

在组件中访问Mutation的方式:

  1. this.$store.commit('Mutation名称')
  2. 先按需导入mapMutations函数:
    <!-- 按正常方法使用 -->
    <button @click="sub">-1</button>
    
    import { mapMutations } from 'vuex'
    methods: {
        ...mapMutations(['add', 'addN'])
        btnHandler1 () {
          // 不带参数
          this.add()
        },
        btnHandler2 () {
          // 带参数
          this.addN(3)
        }
    }
    

Action

mutations中不能编写异步的代码,会导致vue调试器的显示出错。

Action使用

在全局main.js中定义:

new Vuex.Store({
  state: {
    count: 0
  },
  // 只有mutations才有修改state中数据的权力
  mutations: {
    add (state) {
      // 不要在 mutations函数中,执行异步操作
      // setTimeout(() => {
      //   state.count++
      // }, 1000)
      state.count++
    }
  },
  actions: {
    addAsync (context) {
      setTimeout(() => {
        // 在actions中,不能直接修改state中的数据
        // 必须通过context.commit() 触发某个mutation才行
        context.commit('add')
      }, 1000)
    }
  }
})

在组件中访问Action的方式:

  1. this.$store.dispatch('Mutation名称')
  2. 先按需导入mapActions函数:
    <!-- 按正常方法使用 -->
    <button @click="subNAsync">-1 Async</button>
    
    import { mapActions } from 'vuex'
    

Getter

Getter用于对Store中的数据进行加工处理形成新的数据

它只会包装Store中保存的数据,并不会修改Store中保存的数据,当Store中的数据发生变化时,Getter生成的内容也会随之变化

Getter使用

在全局main.js中定义:

new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    showNum (state) {
      return '当前最新的数量是【' + state.count + '】'
    }
  }
})

在组件中访问Getter的方式:

  1. this.$getters.全局数据名称,如:this.$store.getters.showNum
  2. 按需导入mapGettera函数:
import { mapGetters } from 'vuex'

computed: {
    ...mapGetters(['showNum'])// 按计算属性使用
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值