前一段时间因为需要使用vue,特地去学习了一下。但是时间匆忙vuex没有接触到,今天闲暇时看了解了一下vuex,并做了一个小demo,用于记录vuex的简单使用过程。
什么是Vuex?
vuex是专门为vue.js应用程序开发的一种状态管理模式,当多个视图依赖于同一个状态或是多个视图均可更改某个状态时,将共享状态提取出来,全局管理。
下面是一个计数器的例子
在src目录下创建一个store文件夹。
src/store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0,
show: ''
},
getters: {
counts: (state) => {
return state.count
}
},
mutations: {
increment: (state) => {
state.count++
},
decrement: (state) => {
state.count--
},
changTxt: (state, v) => {
state.show = v
}
}
})
export default store
state就是我们的需要的状态,状态的改变只能通过提交mutations,例如:
handleIncrement () {
this.$store.commit('increment')
}
带有载荷的提交方式:
changObj () {
this.$store.commit('changTxt', this.obj)
}
当然了,载荷也可以是一个对象,这样可以提交多个参数。
changObj () {
this.$store.commit('changTxt', {
key:''
})
}
在main.js中引入store.js
import store from './store/store'
export default new Vue({
el: '#app',
router,
store,
components: {
App
},
template: '<App/>'
})
在组件中使用
在组建可以通过$store.state.count
获得状态
更改状态只能以提交mutation的方式。
<template>
<div class="store">
<p>
{{$store.state.count}}
</p>
<el-button @click="handleIncrement"><strong>+</strong></el-button>
<el-button @click="handleDecrement"><strong>-</strong></el-button>
<hr>
<h3>{{$store.state.show}}</h3>
<el-input
placeholder="请输入内容"
v-model="obj"
@change="changObj"
clearable>
</el-input>
</div>
</template>
<script>
export default {
data () {
return {
obj: ''
}
},
methods: {
handleIncrement () {
this.$store.commit('increment')
},
handleDecrement () {
this.$store.commit('decrement')
},
changObj () {
this.$store.commit('changTxt', this.obj)
}
}
}
</script>
到这里这个demo就结束了,
感觉整个个过程就是一个传输数据的过程,有点类似全局变量,但是vuex是响应式的。
这里当然并没有完全发挥出全部的vuex,
vuex还在学习中,写这篇文章主要是记录其简单的使用过程。