安装挂载
- 注意,虽然import xx from 'store.js' 实际执行时会把store.js文件执行一遍,并找到export匹配的项导出
----store.js-------
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
export default store
------main.js-----------
import store from './store.js'
new Vue({
el: '#app',
store
})
state
一般使用(通过computed)this.$store.state
computed: {
count () {
return this.$store.state.count
}
mapState
import { mapState } from 'vuex'
export default {
computed: {
calcWidth () { xxx return xxx },
...mapState(['count'])
}
}
getters
-------store.js-----------
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
一般使用(通过computed) this.$store.getters
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
mapGetters
import { mapGetters } from 'vuex'
computed: {
...mapGetters([
'doneTodosCount',
'anotherGetter',
])
}
mutations
mutations: {
increment (state, n) {
state.count += n
}
}
一般用法(methods)
- 常常只作为methods的一部分
this.$store.commit
methods: {
doSomeThing(){
this.$store.commit('increment')
}
}
mapMutations
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['increment'])
}
actions
- 默认返回promise,且返回值resolve为undefined
- actions里明确return一个promise,则resolve以return的为准
----- store.js---------
actions: {
asyncFuc() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("异步函数调用");
}, 3000);
});
},
},
--------.vue---------
methods:{
dosomething(){
this.$store.dispatch('asyncFuc').then((el) => {
console.log(`${el}-异步`)
})
}
}
一般用法 (methods)
- 方法里包含
this.$store.dispatch
methods:{
doSomething(){
this.$store.dispatch('incrementAsync')
}
}
mapActions
import { mapActions } from 'vuex'
methods: {
...mapActions([ 'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')` ]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
modules命名空间
- 模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。
只有state是私有空间
- 通过添加
namespaced: true
的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。