什么是Vuex及其应用介绍

1、什么是Vuex?
Vuex是专门为Vue.js设计的状态管理库,采用集中方式管理应用的所有组件状态,并以相应的规则保证状态以一种可预测的方式变化。简而言之,就是采用全局模式,将组件的共享状态抽离出来管理,使组件树中每一个位置都可以获取共享的状态或触发行为。
Vuex的核心概念有State, Getter, Mutation, Action, Module。下面简要介绍:
State定义共享状态,即变量;
Getter是基于state的派生状态,可理解为组件中的计算属性;
Mutation是更改状态的唯一方法,通过提交mutation修改状态,同步操作;
Action类似mutation,通过mutation修改状态,支持异步操作;
Module就是模块,在大型项目中为方便状态管理和协作开发,将store拆分为多个子模块,每个模块拥有完整的state, mutation, action, getter。
2、Vuex安装
npm install vuex --save
3、Vuex使用
(1)、创建vuex文件夹,并创建store.js文件
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
})
(2)、在根实例中注册store(main.js)
import store from './vuex/store'

new Vue({
...
store,
...
})
3、store中变量的定义、管理、派生
(1)、state(状态)
在store.js中
const state = {
  name: '小明'
}
export default new Vuex.Store({
  state
})
在应用程序中
<template>
<div>store中的姓名:{{this.$store.state.name}}</div>
</template>

<script>
export default {
  mounted () {
    console.log(this.$store)
  }
}
</script>
(2)、mutation(更改store状态的唯一方法)
在store.js中
const mutations = {
  setName (state) {
    state.name = '小明'
  }
  setNameWithParam (state, param) {
    state.name = param.name
  }
}
export default new Vuex.Store({
  mutations
})
在应用程序中
<script>
export default {
  methods: {
    setNameDefault () {
      this.$store.commit('setName')
    },
    setNameByParam () {
      this.$store.commit({
        type: 'setNameWithParam',
        name: this.name
      })
    }
  }
}
</script>
(3)、action(异步更改状态)
在store.js中
const actions = {
  setNameAsync (context) {
    let _name = context.state.name
    setTimeout(()=>{
      context.commit('setName')
    }, 1000)
  }
  setNameWithParamAsync (context, param) {
    setTimeout(()=>{
      context.commit('setNameWithParam', param)
    }, 1000)
  }
}
export default new Vuex.Store({
  actions
})
在应用程序中
<script>
export default {
  methods: {
    setNameDefaultAsync () {
      this.$store.dispatch('setNameAsync')
    },
    setNameAsync () {
      this.$store.dispatch({
        type: 'setNameWithParamAsync',
        name: this.name
      })
    }
  }
}
</script>
(4)、getter(state的派生状态)
getter可以将对store中某个属性相同的处理操作抽出来,做一个公共的处理。
const getter = {
  formatName: state => {
    let postfix = ''
    if(state.name === '小明'){
      postfix = '很好'
    }
    return state.name + postfix
  },
  customerFormatName: (state)=>(val)=>{
    let postfix = ''
    if(state.name === '小明'){
      postfix = val
    }
    return state.name + postfix
  }
}
export default new Vuex.Store({
  getters
})
在应用程序中
<div>
  <b>{{this.$store.getter.formatName}}</b>
  <b>{{this.$store.getter.customerFormatName('非常好')}}</b>
</div>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

大浪淘沙胡

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

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

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

打赏作者

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

抵扣说明:

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

余额充值