原理

场景:打算开发中大型应用
	特点: 集中式数据管理, 一处修改,多处使用
	思维:
											store

					this.$store.commit('increment')	-> mutations
					this.$store.dispatch('jia')		-> actions

				     mapActions() ->actions							mapGetters()->getters
				学生			代课老师			校长		 	 财务     	版主任		学生
			components - >  actions		->  mutations -> state  <- getters	<-	components
				发送请求      处理			修改状态
							 业务逻辑		修改state			   读取state
							 异步
							  							   state<-$store.state <-  学生

安装 安装包 npm i vuex -s

引入 import vuex from 'vuex
		安装插件 Vue.use(vuex)
		注册到根 new Vue({store})

vue-状态管理
vue-状态管理

①store.js
	引入vue和vuex
实例store对象
let store =new

②main.js注册到根
③在store.js引入actions,mutations,getter,state,写在实例内作为对象

④各个模块单独的js文件内部暴露export

vue-状态管理
vue-状态管理
vue-状态管理

案例,点击让数字从0++

把 mapActions,mapGetters 引入把想action请求的方式写在methods内,然后去往actions
<template>
  <div >
    <h3>vuex</h3>
    <input type="button" value="按钮" @click="jia">
    <hr>
    <!-- {{count}} -->
    <!-- {{this.$store.state.count}} -->
  </div>
</template>

<script>
import vuex from 'vuex'
// console.log(vuex) //vuex={store,mapActions,mapGetters}
// 解构赋值
// import varname from {}
// let varname={}
// let {a,b}={a:1,b:2}
// a→1
// b→2
import {mapActions,mapGetters} from 'vuex'
export default {
  data() {
    return {
      count:0
    }
  },
  methods: {
    jia(){
      // console.log(this.$store)
      // console.log(mapActions,mapGetters)
      // this.$store.dispatch(请求类型,负载,配置)
      this.$store.dispatch('jia',1)

    }
  },
}
</script>

vue-状态管理
vue-状态管理
vue-状态管理

最后完成,如果想直接从state拿数据就在app.vue的
{{this.$store.state.count}}

vue-状态管理

2、上面是comonent直接从state拿的数据,没有通过getters,下面通过getters拿数据

vue-状态管理
vue-状态管理

3、在2里面虽然通过getters拿数据,但是没有用mapActions

在template模板中是
<input type="button" value="按钮" @click="jia(1)">

methods: mapActions(['jia']),

引用types后
vue-状态管理
vue-状态管理
vue-状态管理

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-21
  • 2021-10-12
  • 2021-11-07
  • 2021-08-22
  • 2023-04-04
猜你喜欢
  • 2021-07-23
  • 2021-07-09
  • 2022-12-23
  • 2021-09-02
  • 2022-02-24
  • 2022-12-23
相关资源
相似解决方案