Vue-vuex

Vuex

定义:

  • vue-router同为vue的核心工具
  • Vuex 是一个专为Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化
    注意:
    1.vuex 必须依赖vue文件,在工程化项目开发中,使用Vue.use(vuex)

创建:

1.创建一个Vuex的实例
2.将vuex的实例挂载到vm的根实例中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const store = new Vuex.Store({
state:{count:0},
getters:{
//理解成store的计算属性
str(){console.log(arguments)}
},
mutations:{
// 存储一些公共方法,以便其他组件重复调用
// 它是vuex提供的一种用于修改state中数据的方式
// 必须使用mutations的方法去修改state中的数据
mu_add(state,n){
// 第一个实参是默认的state
// 第二个实参,是我们调用时,自己传的实参,只能写一个参数
// 若有多个参数,则放在一个对象和数组里面
// 通过 this.$store.commit('函数名','我们传递的参数')
n = n || 1
state.count += n
},
},
actions:{
// 可以提供异步方法,比如数据的axios的请求
ac_add(obj,n){
// obj 是vuex封装好的对象,里面提供了commit方法
obj.commit('mu_add',n)
setTimeout(()=>{
obj.commit('mu_add',n)
},1000)
}
// 下面使用es6解构赋值语法,给参数1默认值
ac_add({commit},option){
commit('mu_add',option)
setTimeout(()=>{
obj.commit('mu_add',option)
},1000)
}
}
})


使用:

1.使用vuex中的数据,通过调用this.$store.state.count,使用vuex数据
2.vuex中的数据全放在state中,当state中的某个数据发生改变时,所有用到该数据的地方全都会跟着改变,触发视图的更新
3.通过this.$store.commit('函数名',options),调用mutations中的方法,并默认传参state
4.通过this.$store.dispatch('函数名',options),调用actions中的方法,并默认传参obj对象,对象内置commit方法,再通过调用commit方法,触发mutations中方法执行,达到异步修改数据的目的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const son ={
template:'#son',
data(){
return{
myCount:this.$store.state.count
// 不建议将vuex里面的数据放在组件的data中储存
// 只会给myCount一个初始值,count的变化,并不会再引起view的变化
}
},
computed:{
myCount(){
// 通常将数据放在组件的计算属性中,将属性名依赖于vuex中的数据
return this.$store.state.count
},
...Vuex.mapState(['count','qqq'])
}
}


Vuex中的辅助函数(工程化项目中,推荐使用)

  • …mapState([‘count’,’qqq’])
    • 在组件内部挂载’count’和’qqq’属性
    • 再将’count’映射为:this.$store.state.count
  • …mapGetters([‘arr’])
    • 在组件内部挂载’arr’的计算属性
    • 再将’arr’映射为: this.$store.getters.arr
  • …mapMutations([‘mu_add’])
    • 在组件内部挂载’mu_add’方法
    • 组件直接调用: this.mu_add(10),并传入我们需要的参数
    • 等价于 : this.$store.commit('mu_add',10)

模块化

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}

const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}

const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

-------------本文结束感谢您的阅读-------------