vuex 学习笔记
(一)、 npm install vuex --save
(二)、创建目录结构
|-- store
| |-- actions.js
| |-- getters.js
| |-- mutations.js
| |-- store.js
(三)、引入相关文件并new一个Vuex.Store实例
// sotre.js
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import mutations from './mutations'
import actions from './actions'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
getters,
mutations,
actions
})
(四)、在src目录下的main.js中引入store
// src/main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/store' //引入store
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
(五)、编写mutations
// mutations.js
// mutations中的方法必须是同步的(需要异步的话要使用actions)
// 每个mutation都有一个事件类型(type)和一个事件处理函数(handle)
export default {
increment(state){
state.count += 1
}
}
(六)、编写actions
// actions.js
// action 和 mutation 大致相同,区别是action不直接改变状态,而是通过提交mutation改变状态,而且action可以包含异步操作
export default {
increment({commit}){
commit('increment')
}
}
(七)、编写getters
// getters.js
export default {
getCount(state){
console.log(`count is ${state.count}`)
}
}
(八)、使用store
// App.vue
<template>
<div id="app">
<h1>{{count}}</h1>
<button @click="incre">增加</button>
<button @click="decre">减少</button>
</div>
</template>
<script>
import {mapState, mapMutations, mapGetters, mapActions} from 'vuex'
export default {
name: 'App',
computed:{
...mapState(['count'])
},
methods:{
...mapMutations(['increment', 'decrement']),
...mapGetters(['getCount']),
...mapActions(['increment']),
incre(){
this.increment()
},
decre(){
this.$store.commit('decrement')
}
}
}
</script>
(九)、mapState(['count'])
- 、mapState是一个函数
- 接收一个数组作为参数,数组中的值是在store中定义的state的函数名
- 、mapState返回的是一个对象
-
要在computed属性中进行展开
mapState.jpg
(十)、mapMutations(['increment', 'decrement'])
- mapMutations是一个函数
- 接收一个数组作为参数,数组中的值是在store中定义的mutations的函数名
- mapMutations返回的是一个对象
- 要在methods属性中进行展开
- mutations在调用时要用到
this.$store.commit(函数名)
mapMutations.jpg
(十一)、mapActions(['increment'])
- mapActions是一个函数
- 接收一个数组作为参数,数组中的值是在store中定义的actions的函数名
- mapActions返回的是一个对象
- 要在methods属性中进行展开
- actions在调用时要用到
this.函数名()
mapActions.jpg
(十二)、mapGetters(['getCount'])
- mapGetters是一个函数
- 接收一个数组作为参数,数组中的值是在store中定义的getters的函数名
- mapGetters返回的是一个对象
- 要在methods属性中进行展开
- getters在调用时要用到
this.函数名()
mapGetters.jpg