vue-状态管理

原理


场景:打算开发中大型应用
特点: 集中式数据管理, 一处修改,多处使用
思维:
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})




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

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

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



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

把 mapActions,mapGetters 引入把想action请求的方式写在methods内,然后去往actions
<template>
  <div id="app">
    <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>



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

猜你喜欢

转载自www.cnblogs.com/sansancn/p/11095502.html
今日推荐