VUEX是什么

vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。

image-20201109145007834

vuex的核心概念

state提供唯的公共数据源,所有共享的数据都要统一放到 Store的 State中进行存储。

1
2
3
4
5
6
7
8
9
export default new Vuex.Store({
// 共享数据
state: {
count: 0
},
mutations: {},
actions: {},
modules: {}
})

使用方式

  1. 通过this.$store.state访问属性

    1
    <h3>当前最新的Count值为:{{ $store.state.count }}</h3>

    template模板中可以省略this

  2. 导入模式

    通过计算属性

    1
    2
    3
    4
    5
    6
    7
    8
    9
    import { mapState } from 'vuex'
    export default {
    data () {
    return {}
    },
    computed: {
    ...mapState(['count'])
    }
    }

    此时就可以把count当作成为一个计算属性。

Mutation用于变更store的数据。但不能使用异步操作

在vuex对象中定义方法

1
2
3
4
5
6
7
8
9
mutations: {
add(state) {
// 变更状态
state.count++
},
sub(state) {
state.count--
}
},

在组件中调用

1
2
3
4
5
methods: {
add () {
this.$store.commit('add')
}
}

方法也可以传递参数,在mutations方法接受参数时第一个参数总是state,之后可以在调用时传入参数

1
2
3
4
addN (state, step) {
// 变更状态
state.count += step
},
1
2
3
addN (step) {
this.$store.commit('addN', step)
}
1
<button @click="addN(3)">+3</button>

Mutation同样可以映射成组件的方法。

1
2
3
4
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['sub'])
}

如果通过异步操作变更数据,必须通过 Action,而不能使用 Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据

1
2
3
4
5
6
7
8
actions: {
// actions 不能直接修改state中的数据 必须通过context.commit触发
AsyncAdd (context) {
setTimeout(() => {
context.commit('add')
}, 1000)
}
},
1
2
3
AsyncAdd () {
this.$store.dispatch('AsyncAdd')
}

actions也可以携带参数,方法与Mutation类似。同样可以使用导入的方式

1
2
3
4
import { mapActions } from 'vuex'
methods: {
...mapActions(['sub'])
}

Getter用于对 Store中的数据进行加工处理形成新的数据

1
2
3
4
5
getters: {
showNum: state => {
return '当前最新数量是' + state.count
}
},
  1. 直接使用

    1
    this.$store.getters.名称
  2. 导入使用

    1
    2
    3
    4
    import { mapGetters } from 'vuex'
    computed: {
    ...mapGetters(['showNum'])
    }