#vuex的Store简单使用过程
介绍
Store的代码结构一般由State、Getters、Mutation、Actions这四种组成,也可以理解Store是一个容器,Store里面的状态与单纯的全局变量是不一样的,无法直接改变store中的状态。想要改变store中的状态,只有一个办法,显示地提交mutation。
1.
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
getters:{
},
mutations: {
},
actions: {
}
})
简单的Store
2.修改组件HelloWorld,开始使用Store里注册的新状态
<template>
<div class="hello">
<h1>{{ this.$store.state.count }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
- 看效果
3.往store.js里的mustations添加改变状态值的加减功能,
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count:1
},
mutations: {
addmu(state){state.count++},
lessmu(state){state.count--}
},
actions: {
}
})
4.回到HelloWorld组件, 添加增加和减少按钮,用来提交store的mutation
<template>
<div class="hello">
<h1>{{ this.$store.state.count }}</h1>
<div>
<button @click="addfn()">增加</button>
<button @click="lessfn()">减少</button>
</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
},
methods:{
addfn(){
//提交名为addmu的mutations
this.$store.commit('addmu');
},
lessfn(){
//提交名为lessmu的mutations
this.$store.commit('lessmu');
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
效果如下
由于mutation必须同步执行的限制,不方便实现复杂的功能。不过,别担心,看见了那个Actions吗?它就不受约束!我们可以在
它内部执行异步操作
5.修改store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count:1
},
mutations: {
addmu(state){state.count++},
lessmu(state){state.count--}
},
actions: {
addac({commit}){commit('addmu')},
lessac({commit}){commit('lessmu')}
}
})
6.修改HelloWorld组件,将提交mutation改为分发Action,Actions支持载荷方式和对象方式
<template>
<div class="hello">
<h1>{{ this.$store.state.count }}</h1>
<div>
<button @click="addfn()">增加</button>
<button @click="lessfn()">减少</button>
</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
},
methods:{
addfn(){
//以载荷方式分发
this.$store.dispatch('addac');
},
lessfn(){
//以对象方式分发
this.$store.dispatch({type:'lessac'});
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>