Vuex的学习总结

Vuex的核心

  1. State
  2. Mutation
  3. Action
  4. Getter

state

state提供唯一的公共数据源,所有共享的数据都要统一放到store中的state中存储
在组件中访问State的方式:
1).this.$store.state.全局数据名称

this.$store.state.count

2).先按需导入mapState函数:

 import { mapState } from 'vuex'

然后数据映射为计算属性:

computed:{ ...mapState(['全局数据名称']) }

Mutation

Mutation用于修改变更$store中的数据,打开store.js文件,在mutations中添加代码如下

mutations: {
    方法名 (state,step){
      //第一个形参永远都是state也就是$state对象
      //第二个形参是调用方法时传递过来的参数
      ...
    }
  }
  • 使用this.$store.commit(‘方法名’,要传递的参数)
  • 导入import { mapMutations } from ‘vuex’,
    使用展开运算符
methods:{
  ...mapMutations(['方法名'])
}

Action

在mutations中不能编写异步的代码,会导致vue调试器的显示出错,在vuex中我们可以使用Action来执行异步操作。
在store.js文件,修改Action

actions: {
  方法名 (context,step){
		...
      context.commit('方法',step);
   
  }
}
  • 使用this.$store.dispatch(‘方法名’,step)
  • 导入import { mapActions } from ‘vuex’
    在方法容器中使用 …mapMutations映射为实例方法
methods:{
  ...mapMutations(['方法名'])
}

Getter

Getter用于对Store中的数据进行加工处理形成新的数据,不会改变Store中保存的数据
在store.js文件,添加getters

export default new Vuex.Store({
  .......
export default new Vuex.Store({
  .......
  getters:{
    //添加了一个showNum的属性
    showNum : state =>{
      return '最新的count值为:'+state.count;
    }
  }
})
  • 使用{{$store.getters.showNum}}获取
  • 导入import { mapGetters } from ‘vuex’
    映射为计算属性
computed:{
  ...mapGetters(['showNum'])
}

安装Vuex

npm install vuex --save

导入vuex包

import Vuex from 'vuex'
Vue.use(Vuex)

新建store.js,创建store对象

const store =new Vuex.store({
//state中存放的就是全局共享的数据
state:{count:0}
})

将store对象挂载到vue示例中

import Vue from 'vue'
import App from './App.vue'
import store from './store.js'
new Vue({
  store,
  render: h => h(App)
}).$mount('#app')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值