50 行代码解释 Vuex 基础使用

在这里插入图片描述

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化

在这里插入图片描述

如果在初始化项目时,选择了安装 vuex,那么无需进行这一步的安装。

安装 npm insatll vuex --save

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  // 存储你想要的值(一个仓库的作用)
  state: {
    count: 0,
    str: "abcd234",
    dataList: []
  },
  // 对数据做进一步的处理
  getters: {
    strLen: state => state.str.length
  },
  // mutations,用来改变 state 中的值。当然只能是同步操作
  mutations: {   
    increment(state, payload) {
      // 改变state中的数据
      state.count = payload.number;
    },
    changeData(state, payload) {
      state.dataList = payload
    }
  },
  // actions 可以是异步操作
  actions: {
    getSong({ commit }, id) {
      fetch('https://api.github.com/repos/vmg/redcarpet/issues?state=closed').then(res => res.json().then(res => {
        commit('changeData', res)
      }))
    }
  }
})

我们使用 console.logvuex 打印出来

{
    Store: ƒ Store(options)
	createLogger: ƒ createLogger(ref)
	createNamespacedHelpers: ƒ (namespace)
	install: ƒ install(_Vue)
	mapActions: ƒ (namespace, map)
	mapGetters: ƒ (namespace, map)
	mapMutations: ƒ (namespace, map)
	mapState: ƒ (namespace, map)
}

Vuex 实际上是一个对象,包含 Store这一构造函数,mapActionsmapGettersmapMutationsmapState这几个辅助方法

获取 state 中的值
<p>{{ this.$store.state.count }}</p>

如果状态过多,这样的写法也是很麻烦的,Vuex 中提供了 mapState。

import { mapState } from 'vuex'

export default {
  computed: {
    ...mapState(['count'])
  },
}

这样页面当中就可以直接使用 count 变量了。

<h1>{{ count }}</h1>
获取 Getter 中的值
<h2>Getters: {{ this.$store.getters.strLen }}</h2>

或者使用 Vuex 中提供了 mapGetters

computed: {
  ...mapGetters(['strLen'])
},
修改 state 中的值

对于在 store 中编写的 increment 方法。

handleClick() {
  this.$store.commit('increment', {
    number: 10
  })
}

Vuex 中提供了 mapMutations

export default {
  methods: {
    ...mapMutations(['increment']),
    handleClick() {
      this.increment({ number: 10})
    }
  },
}

实际开发中,会有很多处理异步的操作,最典型的莫过于获取服务端数据。Vuex 允许在 action 中进行异步操作。

action 中需要 commit 一个 mutation。

getData() {
  this.$store.dispatch('getSong')
}

Vuex 中提供了 mapActions

methods: {
  ...mapActions(['getSong']),
  getData() {
    this.getSong()
  }
},

对于一个仓库而言,如何获取值与设置值才是最重要的,剩下的都是花里胡哨的招式。

总结:

获取值使用 this.$store.state 或者是 mapState。如果希望对获取的值进行处理,可以使用 getter,获取 getter 使用 this.$store.getters 或者是 mapGetters
值的修改,对于同步操作,可以在 mutations 中编写,使用该方法可以通过 this.$store.commit 或者是 mapMutations。对于异步操作,可以在 actions 中编写,使用该方法可以通过 this.$store.dispatch 或者是 mapActions

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值