Vuex状态管理(全家桶)

什么是vuex状态管理?

就是我们vue里的核心数据库

1. 安装

$ npm install vuex --save

2. 在main.js 主入口js里面引用store.js

import Vue from 'vue'
import App from './App'
import router from './router' 
import store from './vuex/store'   //引用store.js
Vue.config.productionTip = false  //阻止在启动时生成生产提示 

//vue实例
new Vue({
  el: '#app',
  router,
  store,                           //把store挂在到vue的实例下面
  template: '<App/>',
  components: { App }
})

3. 在store.js里引用Vuex

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)  //注册Vuex

// 定义常量    如果访问他的话,就叫访问状态对象
const state = {
    count: 1
}

// mutations用来改变store状态,  如果访问他的话,就叫访问触发状态
const mutations = {
    //这里面的方法是用 this.$store.commit('jia') 来触发
    jia(state){
        state.count ++
    },
    jian(state){
        state.count --
    },
}
//暴露到外面,让其他地方的引用
export default new Vuex.Store({
    state,
    mutations
})

4. 在vue组件中使用

使用$store.commit('jia')区触发mutations下面的加减方法

<template>
  <div class="hello">
      <h1>Hello Vuex</h1>
      <h5>{{$store.state.count}}</h5>
      <p>
        <button @click="$store.commit('jia')">+</button>
        <button @click="$store.commit('jian')">-</button>
      </p>
  </div>
</template>

<!-- 加上scoped是css只在这个组件里面生效,为了不影响全局样式 -->
<style scoped>
    h5{
      font-size: 20px;
      color: red;
    }
</style>

5. 查看演示

QQ20171101-172703-HD.gif

6. state访问状态对象

使用computed计算

<template>
  <div class="hello">
      <h1>Hello Vuex</h1>
      <h5>{{count}}</h5>
      <p>
        <button @click="$store.commit('jia')">+</button>
        <button @click="$store.commit('jian')">-</button>
      </p>
  </div>
</template>

<script>
import {mapState} from 'vuex'
export default{
    name:'hello', //写上name的作用是,如果你页面报错了,他会提示你是那个页面报的错,很实用
    // 方法一
    // computed: {
    //   count(){
    //     return this.$store.state.count + 6
    //   }
    // }
    
    // 方法二 需要引入外部 mapState
    computed:mapState({
      count:state => state.count + 10
    })
  
    // ECMA5用法
    // computed:mapState({
    //   count:function(state){
    //     return state.count
    //   }
    // })
    
    //方法三
    // computed: mapState([
    //   'count'
    // ])
  }
</script>

7. mutations触发状态 (同步状态)

<template>
  <div class="hello">
      <h1>Hello Vuex</h1>
      <h5>{{count}}</h5>
      <p>
        <button @click="jia">+</button>
        <button @click="jian">-</button>
      </p>
  </div>
</template>
<script>
import {mapState,mapMutations} from 'vuex'
  export default{
    name:'hello', //写上name的作用是,如果你页面报错了,他会提示你是那个页面报的错,很实用
    //方法三
    computed: mapState([
      'count'
    ]),
    methods:{
      ...mapMutations([
          'jia',
          'jian'
      ])
    }
  }
</script>

8. getters计算属性

getter不能使用箭头函数,会改变this的指向

在store.js添加getters

// 计算
const getters = {
    count(state){
        return state.count + 66
    }
}

export default new Vuex.Store({
    state,
    mutations,
    getters
})
//count的参数就是上面定义的state对象
//getters中定义的方法名称和组件中使用的时候一定是一致的,定义的是count方法,使用的时候也用count,保持一致。

组件中使用

<script>
  import {mapState,mapMutations,mapGetters} from 'vuex'
  export default{
    name:'hello',
    computed: {
      ...mapState([
        'count'
      ]),
      ...mapGetters([
        'count'
      ])
    },
    methods:{
      ...mapMutations([
          'jia',
          'jian'
      ])
    }
  }
</script>

9. actions (异步状态)

在store.js添加actions

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

// 定义常量
const state = {
    count: 1
}

// mutations用来改变store状态  同步状态
const mutations = {
    jia(state){
        state.count ++
    },
    jian(state){
        state.count --
    },
}
// 计算属性
const getters = {
    count(state){
        return state.count + 66
    }
}
// 异步状态
const actions = {
    jiaplus(context){
        context.commit('jia') //调用mutations下面的方法
        setTimeout(()=>{
            context.commit('jian')
        },2000)
        alert('我先被执行了,然后两秒后调用jian的方法')
    },
    jianplus(context){
        context.commit('jian')
    }
}

export default new Vuex.Store({
    state,
    mutations,
    getters,
    actions
})

在组件中使用

<template>
  <div class="hello">
      <h1>Hello Vuex</h1>
      <h5>{{count}}</h5>
      <p>
        <button @click="jia">+</button>
        <button @click="jian">-</button>
      </p>
      <p>
        <button @click="jiaplus">+plus</button>
        <button @click="jianplus">-plus</button>
      </p>
  </div>
</template>
<script>
  import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
  export default{
    name:'hello',
    computed: {
      ...mapState([
        'count'
      ]),
      ...mapGetters([
        'count'
      ])
    },
    methods:{
      // 这里是数组的方式触发方法
      ...mapMutations([
          'jia',
          'jian'
      ]),
      // 换一中方式触发方法 用对象的方式
      ...mapActions({
        jiaplus: 'jiaplus',
        jianplus: 'jianplus'
      })
    }
  }
</script>

<style scoped>
    h5{
      font-size: 20px;
      color: red;
    }
</style>

10. modules 模块

适用于非常大的项目,且状态很多的情况下使用,便于管理

修改store.js

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

const state = {
    count: 1
}
const mutations = {
    jia(state){
        state.count ++
    },
    jian(state){
        state.count --
    },
}
const getters = {
    count(state){
        return state.count + 66
    }
}
const actions = {
    jiaplus(context){
        context.commit('jia') //调用mutations下面的方法
        setTimeout(()=>{
            context.commit('jian')
        },2000)
        alert('我先被执行了,然后两秒后调用jian的方法')
    },
    jianplus(context){
        context.commit('jian')
    }
}

//module使用模块组的方式  moduleA
const moduleA = {
    state,
    mutations,
    getters,
    actions
}

// 模块B moduleB
const moduleB = {
    state: {
        count:108
    }
}

export default new Vuex.Store({
    modules: {
        a: moduleA,
        b: moduleB,
    }
})
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 3,070评论 0 6
  • vuex 场景重现:一个用户在注册页面注册了手机号码,跳转到登录页面也想拿到这个手机号码,你可以通过vue的组件化...
    sunny519111阅读 7,971评论 4 111
  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 2,901评论 0 7
  • vuex是什么鬼? 如果你用过redux就能很快的理解vuex是个什么鬼东西了。他是vuejs用来管理状态的插件。...
    麦子_FE阅读 6,819评论 3 37
  • Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应...
    白水螺丝阅读 4,617评论 7 61