# Vuex 学习笔记
标签(空格分隔): vuex 数据存储
---
## 1. 安装与配置
+ npm i vuex -S
+ 配置步骤
1. 在项目入口文件中导入vuex并挂载
```
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
```
2. 在src文件中创建store文件夹,并在文件夹下创建vuex.js文件,在vuex.js中创建store对象,并向外部暴露
```
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//数据存放在state中
const state = {
name: 'huwenwei',
age: 18,
gender: 'male',
number: 0,
info: ''
}
//getters 对数据进行处理,可以理解为计算属性
const getters = {
changeNumber: (state) => {
return state.number + 100
}
}
// mutations 对数据进行修改的函数,注意:只能进行同步操作
const mutations = {
showInfo (state) {
state.info = '我的名字叫' + state.name
}
}
// actions 类似mutations, 不同的是,可以进行异步操作
const actions = {
changeAge (context) { //context 上下文的意思,这里是store实例
setTimeout(() => {
console.log('changeAge起作用了')
context.commit('showInfo')
}, 2000)
}
}
//new 一个store对象,向外部暴露
export default new Vuex.Store({
state,
getters,
mutations,
actions
})
```
3. 在入口文件中导入store文件中的vuex.js,并在Vue实例中注册store
```
import store from './store/vuex'
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
```
4. 至此,vuex的store中的数据和方法已经能够在各个组件中使用了
## 2. vuex在组件中的使用
+ 原始使用方法
```
```
+ 使用辅助函数使用
```
//通过引入辅助函数,之后把需要用的函数导入到methods中,把属性、计算属性导入到computed中,之后就能在组件中直接用响应的名字来使用响应的属性和方法了,(这里的对应关系辅助函数已经处理好了)
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
data: () => ({
}),
methods: {
...mapActions(['changeAge']),
...mapMutations(['showInfo'])
},
computed: {
...mapState([ "name" , "age" ,"gender" ,"number" ,"info"]),
...mapGetters(["changeNumber"])
}
}
</script>
```