走进Vuex的世界
1. 什么是vuex
Vuex是一个专为Vue.js应用程序开发的状态管理模式。
2. vuex的5大核心
- state 基本数据
- getters 从基本数据中派生的数据
- mutations 提交更改数据的方法 同步
- actions 像一个装饰器,包裹mutations,使他异步
- modules 模块化vuex
3. Vuex优缺点
- 优点
- 方便组件间传值
- 减少axios 请求的次数
- 缺点
1.刷新浏览器,vuex的数据会变为初始状态
4. 应用
npm install vuex
export default new Vuex.Store({
state: {
age: 1
}
})
- 在test.vue中获取 age
// 首先先引入 mapState
import {mapState} from 'vuex'
// 在computed中
computed: {
...mapState(['age'])
}
//在页面中应用
<template>
<div>
{{age}}
</div>
</template>
export default new Vuex.Store({
state: {
age: 1
},
getters: {
gettersMethods(state) {
if (state.age > 2) {
return "该数字大于2"
} else {
return "该数字小于等于2"
}
}
}
})
<template>
<div>
{{age}}
<input type="button" value="+" @click="increment" />
{{gettersMethods}}
</div>
</template>
<script>
import {mapState,mapGetters} from 'vuex'
export default {
name: "Test",
computed: {
...mapState(['age']),
...mapGetters(['gettersMethods'])
}
}
</script>
export default new Vuex.Store({
state: {
age: 1
},
mutations: {
add(state) {
state.age++;
}
}
})
//test.vue 代码
<template>
<div>
{{age}}
<input type="button" value="+" @click="add" />
</div>
</template>
<script>
import {mapState, mapMutations} from 'vuex'
export default {
name: "Test",
computed: {
...mapState(['age'])
},
methods: {
...mapMutations(['add'])
}
}
</script>
<style scoped>
</style>
点击 + 数字会相加
export default new Vuex.Store({
state: {
age: 1
},
mutations: {
add(state) {
state.age++;
},
},
actions: {
increment (context) { //官方给出的指定对象, 此处context可以理解为store对象
context.commit('add');
}
},
modules: {}
})
//test.vue中代码
<template>
<div>
{{age}}
<input type="button" value="+" @click="increment" />
</div>
</template>
<script>
import {mapState, mapMutations,mapActions} from 'vuex'
export default {
name: "Test",
computed: {
...mapState(['age'])
},
methods: {
...mapMutations(['add']),
...mapActions(['increment'])
}
}
</script>
<style scoped>
</style>