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})

1666447-20190627094625378-1524356960.png
1666447-20190627094656490-449812681.png


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

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

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

1666447-20190627094840680-155808923.png
1666447-20190627095633124-644355362.png
1666447-20190627095639064-1890180053.png

案例,点击让数字从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>

1666447-20190627101839827-1218932237.png
1666447-20190627101858494-447779748.png
1666447-20190627101927995-677222917.png

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

1666447-20190627102106327-1545878250.png

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

1666447-20190627140327519-530459936.png
1666447-20190627140404395-2039903593.png

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

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

methods: mapActions(['jia']),

引用types后
1666447-20190627145255339-1958695048.png
1666447-20190627145324679-1086968947.png
1666447-20190627145418807-2030375274.png

转载于:https://www.cnblogs.com/sansancn/p/11095502.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值