vuex
vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
使用vuex
安装
1
npm install vuex --save
main.js
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
32import Vue from 'vue'
// 1.引入vuex包
import Vuex from 'vuex'
// 2. 手动安装vuex
Vue.use(Vuex);
// 3.创建一个store实例
let store = new Vuex.Store({
state: { // 类似以data
count: 1
},
mutations: { // 数据仓库管理员,类似于methods,其中的方法第一个参数都是state
increment(state){
state.count++
},
reduce(state, n){
state.count -= n
}
},
getters: { // state中的数据需要一层包裹时使用getters
showCount(state){
return '最终结果是:' + state.count
}
}
});
import app from './app.vue';
let vm = new Vue({
el: '#app',
data: {},
render: c => c(app), // run-time模式需要用render渲染组件
store // 4.挂载store
});使用
1
<h3>{{ $store.getters.showCount }}</h3>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19<template>
<div>
<input type="button" value="减少" @click="minus">
<input type="button" value="增加" @click="plus">
<input type="text" v-model="$store.state.count">
</div>
</template>
<script>
export default {
methods: {
plus(){
this.$store.commit('increment')
},
minus(){
this.$store.commit('reduce', 5)
}
}
}
</script>总结:
- state中的数据不能直接修改,如需修改必须通过mutations:this.$store.commit(‘方法名’, 唯一参数)
- 组件直接从state中获取数据:this.$store.state.***
- 如果store中state的数据在对外提供的时候需要一层包装就使用getters,这时使用数据:this.$store.getters.***