Vuex

安装 Vuex

npm install --save vuex
// 创建Vuex实例    src > store > index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
    state: {},    getters: {},    mutations: {},    actions: {},    modules: {}
})

// 注册Vuex插件    src > main.js
import store from './store'
new Vue({    ... store ...    }).$mount('#app')

Vuex 概述

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
采用集中式存储来管理应用的所有组件的状态。
可以实现应用中多个组件的共享状态进行集中式的管理(读 / 写)。
应用场景:用户选项、登录信息、社交通知、电商购物车、文章已读/未读状态
Vuex与全局对象的区别:
每个 Vuex 应用的核心就是 store 容器,它包含着应用中大部分的状态 state
1… Vuex 的状态存储是响应式的:
Vue组件读取store中状态时,若store中的状态发生变化,则相应组件也会得到高效更新
2… 不能直接改变 store 中的状态:
改变store中的状态的唯一途径就是显式地提交(commit) mutation
在这里插入图片描述
State
Getters
Mutations commit()
Actions dispatch()
Modules
mapState( )
mapGetters( )
mapMutations( )
mapActions( )

State

定义了应用状态的数据结构,数据类型有 string、number、array、object、function 等

// html
{{    this.$store.state.username    }}
{{    $store.state.user.age > 17 ? '曹老铁' : '小小曹'    }}
<p v-for="(item,key) in $store.state.extends" :key="key">
    {{ key }} {{ item.username }} {{ item.age }}
</p>

// store
state: {
    username: 'caocao',
    user:     {username: 'caocao', age: 17},
    extends:  [  {username: 'caocao', age: 17}  ]
}

Getters

store 的计算属性,getter 的返回值会根据它的依赖值被缓存起来,其依赖值改变时它才会被重新计算。

// html
{{  $store.getters.goldenHouse  }}
{{  $store.getters.count  }}
{{  $store.getters.getUserByIndex(0)  }}

// store
getters: {
    goldenHouse(){    return '甄宓、貂蝉、大乔、小乔......'    },
    count(state) {    return state.extends.length    },
    getUserByIndex(state){
        return function(index){    return state.extends[index]    }
    }
}

Mutations

mutations 是状态改变操作方法,也是 Vuex修改 state的唯一推荐方法,其他修改方式在严格模式下将会报错。
每个 mutation都有一个字符串的事件类型 (type) 和一个回调函数 (handler)。
这个回调函数就是进行状态更改的地方,并且它会接受 state作为第一个参数,
该方法只能进行同步操作,且方法名只能全局唯一,操作中会有一些 hook暴露出来,以进行state的监控等

mutations: {      type: function( state[,payload] ){ ... }      }
// html
<button @click="minus">-</button>  {{ $store.state.user.age }}  <button @click="add">+</button>

// js
methods: {
    minus(){    this.$store.commit('decrement')    },
    add  (){    this.$store.commit('increment')    }
}

// store
mutations: {
    decrement:  state  => {  state.user.age--  },
    increment  (state)    {  state.user.age++  }
}
// html
<p>用户:<input type="text" v-model="username"></p>
<p>年龄:<input type="text" v-model="age"></p>
<p><button @click="addUser">添加用户</button></p>

// js
data(){
    return {    username: '',  age: ''    }
},
methods: {
    addUser(){
        var payload = {    username: this.username,  age: this.age    }
        this.$store.commit('addUser',payload);
    }
}

// store
mutations: {
    addUser( state, payload ){    state.extends.push(payload)    }
}

Actions

Actions 类似于 mutations,不同在于:
1、Actions 提交的是 mutation,而不是直接变更状态
2、Actions 可以包含任意异步操作,专门用于发送 ajax请求
在这里插入图片描述

actions: {      type: function(context,payload){ ... }      } 
// context 运行环境           
// html
<button @click="getServerData">获取服务器数据</button>    {{ $store.state.extends }}

// js
methods: {
    getServerData(){    this.$store.dispatch( 'getUserData' )    }
}

// store
actions: {
    getUserData(context){
        var data = {    username: 'liubei',  age: 17    }           // 模拟ajax
        context.commit( 'addUser', data );
    }
}

Modules

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。
当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许将store分割成模块 (module) 。
每个模块拥有自己的 state、mutation、action、 getter 甚至是嵌套子模块——从上至下进行同样方式的分割

const moduleA = {
     state: {},    getters: {},    mutations: {},    actions: {}
}
const moduleB = {
     state: {},    getters: {},    mutations: {},    actions: {}
}
const store = new Vuex.Store({
    modules: {
        a: moduleA,
        b: moduleB
    }
});

实例方法 commit( )

Vuex 不能直接改变 store 中的状态,必须用 commit 显式地提交 mutation

// 结构
// type 参数用于指定事件类型                 
// payload 提交负载,向 store.commit传入额外参数,通常为对象
commit( type: string, payload?: any )        
commit( mutation: Object ) 
commit( 'mutation名', 'payload传参' )

// 用法
methods: {
    store.commit( 'increment', {
        amount: 10
    })
}
methods: {
    store.commit({
        type: 'increment',
        amount: 10
    })
}

实例方法 dispatch( )

用于分发 action,Actions 通常请求 ajax数据

// 结构
// type 参数用于指定事件类型
// payload 提交负载,向 store.dispatch传入额外参数,通常为对象
dispatch( type: string, payload?: any )        
dispatch( action: Object )                     

// 用法
methods: {
    getServerData(){    this.$store.dispatch( 'getUserData' )    }
}

Vuex 辅助函数

将需要的 state、getter、mutation、action 拉入当前页面组件,自定义前缀,方便调用,减少码量


mapState( )

为组件创建计算属性以返回 Vuex store 中的状态

computed: {
    mapState(    map:    Array | Object/Function    )
}
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
    computed: {  
        ...mapState([                                 // ... 对象展开运算符                           
            'username', 'gender', 'age'               // 将Vuex属性变为了组件自己的属性
        ]),
        ...mapState([
            extension: 'extends'         // 保留关键字 extends,必须赋别名,以对象形式呈现
        ])
    }
}

{{    username    }}                                 // 成功显示
{{    extension.username    }}                       // 成功显示

mapGetters( )

为组件创建计算属性以返回 getter 的返回值

computed: {
    mapGetters(    map:    Array | Object    )
}
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
    computed: {  
        ...mapGetters([
            jinWu: 'goldenHouse'
        ])
    }
}

{{  jinWu  }}           // 甄宓、貂蝉、大乔、小乔......

mapMutations( )

用于创建组件方法提交 mutation

methods: {
    mapMutations(    map:    Array | Object/Function    )
}
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'

methods: {  
    ...mapMutations([
        sIncrement: 'increment',
        sDecrement: 'decrement'
    ]),
    minus(){
        // this.$store.commit('decrement')
        this.sdecrement()
    },
    add(){
        // this.$store.commit('increment')
        this.sincrement()
    }
}
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'

methods: {  
    ...mapMutations([
        'addUser'
    ]),
    addUser(){
        var payload = {    username: this.username,  age: this.age    }
        // this.$store.commit('addUser',payload);
        this.addUser(payload);
    }
}
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'

computed: {  
    ...mapGetters([
        geUsertByI: 'getUserByIndex'
    ])
}

mapActions( )

用于创建组件方法分发 action

methods: {
    mapActions(    map:    Array | Object/Function    )
}
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'

methods: {  
    ...mapActions([
        'getUserData'
    ]),
    getServerData(){
        // this.$store.dispatch( 'getUserData' );
        this.getUserData();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值