js——Vuex相关用法

js——Vuex相关用法

平时在一个vue组件中,里面的数据和方法只有在但当前的.vue组件中可以访问和使用,其他的组件是无法访问的。但是在实际的业务逻辑中,经常有跨组件数据的需求,因此,Vuex的设计就是为了用来统一管理组件状态的。它定义了一系列的规范来使用和操作数据,使组件应用更加高效。

###Vuex的基本用法:

首先通过NPM安装Vuex:

npm install –save vuex

在main.js中通过Vue.use()使用Vuex:

store包含了应用的数据(状态)和操作过程。任何组件使用同一store的操作的数据时,只要store的数据发生变化,对应的组件也会立刻更新。

在任何组件内,可以直接通过$store.state.count 读取这个数据:

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
<template>
<div class="hello">
<p>{{$store.state.count}}</p>
<button @click="handleIncrement">+1</button>
<button @click="handleDecrease">-1</button>
</div>
</template>

<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
methods:{
handleIncrement () {
this.$store.commit('increment');
},
handleDecrease () {
this.$store.commit('decrease');
}
}
}
</script>

当然,以上$store.state.count亦可以换成count,然后后面加上:

1
2
3
4
5
computed:{
count(){
return this.$store.state.count;
}
}

在组件内,来自store的数据只能读取,不能手动改变,改变store数据的唯一途径就是显式的提交mutatations。他是Vuex的第二个选项,用来直接修改state里的数据。

###相关选项

Vuex还有其他的三个选项可以使用:getters、actions、modules。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
getters:{
getNum:state => {
return state.list.filter(item => item < 10);
},
listCount:(state,getters) => {
return getters.getNum.length;
}
}

//.vue文件中
computed:{
count(){
return this.$store.state.count;
},
listCount () {
return this.$store.getters.listCount;
}
}

这里,getter也可以依赖于其他的getter,把getter作为第二个参数。如上例中的listCount。

注意的是,mutation里面不应该出现异步操作的数据,因此有了actions,他和mutation很像,但是提交的是mutation,并且可以异步操作业务逻辑。

action在组件中通过$store.dispatch触发,例如使用action加一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//main.js
actions:{
increment (context) {
context.commit('increment')
}
}
//.vue
methods:{
handleIncrement () {
this.$store.dispatch('increment');
},
handleDecrease () {
this.$store.commit('decrease');
}
},

下面是处理异步操作的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//main.js
actions:{
increment (context) {
return new Promise(resolve =>{
setTimeout(()=>{
context.commit('increment');
resolve();
},1000)
})
}
}
//.vue
methods:{
handleIncrement () {
this.$store.dispatch('increment').then(()=>{
console.log(this.$store.state.count)
});
},
handleDecrease () {
this.$store.commit('decrease');
}
},

mutation和actions看起来很相似,但一般涉及改变数据的时候用Vue,存在业务逻辑的时候用actions。

###module的用法

最后一个是module,主要是用来将store分割到不同的模块,微地就是让main.js中的store看起来更友好。

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
var moduleA = {
state:{
count:0
},
mutations:{
hello(){
console.log('hello')
}
}
}

var moduleB = {
state:{
count:1
},
mutations:{
get(state){
console.log('state=' + state.count)
}
}
}

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