vuex使用心得-state的使用

首选我们创建一个基本的vuex的实例

1
2
3
4
5
6
7
8
const store=new Vuex.Store({
state:{
msg:'hello,vuex state'
},
mutations:{},
getters:{},
actions:{}
})

注意new Vuex.Store是固定写法,以前手贱写成store,,直接飘红
state项目对象里面存放的就是各种状态(其他的几个选项对象后面逐一讲解),类似于vue实例里面的data选项对象。

在state里面创建好了状态,在页面或者组件中怎么使用呢?

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
<div id="app">
<h1>{{msg}}</h1>
<div>{{$store.state.count}}</div>
<count></count>
</div>
<script>
const count={
template:'<div>{{this.$store.state.count}}</div>'
}
const store=new Vuex.Store({
state:{
count:0
}
})
new Vue({
el:'#app',
data:{
msg:'vuex state的使用'
},
components:{
count
},
store
})
</script>

在vue的根实例中添加store选项对象,该store实例会注入到所有的组件中,在子组件中可以通过this.$store获取到,所有要获取到vuex中的count,我们可以通过this.$store.state.count

细心的小伙伴可能发现了,在子组件中每次要使用state中的状态,都要使用this.$store.state这种形式,实在是太麻烦了,能不能直接绑定状态名count呢?答案肯定是有的。

方法一,使用computed,定义和state里面相同名字的计算属性,然后在组件模板里直接使用计算属性

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
<div id="app">
<h1>{{msg}}</h1>
<counter></counter>
</div>
<script>
let counter={
template:`<div>{{this.$store.state.count}}--{{count}}</div>`
}
const store=new Vuex.Store({
state:{
count:1
}
});
new Vue({
el:'#app',
data:{
msg:"vuex state"
},
computed:{
count(){
return this.$store.state.count
}
},
components:{
counter
},
store
})
</script>

方法一的话,虽然在模板里面简化了,但是必须要定义相同名称的计算属性,还是有些麻烦。

方法二,使用mapState

首先引入,import {mapState} from ‘vuex’
然后改写computed
`
computed:{
…map([‘count’,’msg’])
}
//把要使用的state状态放到数组里面


上一篇
koa2 koa2
测试koa2
2018-05-17 刘赛
下一篇
vuex使用心得-vuex的使用场景 vuex使用心得-vuex的使用场景
vuex是vue全家桶中不可或缺的部分,按照官方的说明,vuex是一个专门为vue应用程式开发的状态管理模式。 Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状
2017-07-01 刘赛