7、VUEX
VUEX是什么
vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。
vuex的核心概念
state提供唯的公共数据源,所有共享的数据都要统一放到 Store的 State中进行存储。
export default new Vuex.Store({
// 共享数据
state: {
count: 0
},
mutations: {},
actions: {},
modules: {}
})使用方式
通过
this.$store.state访问属性<h3>当前最新的Count值为:{{ $store.state.count }}</h3>在
template模板中可以省略this导入模式
通过计算属性
import { mapState } from 'vuex' export default { data () { return {} }, computed: { ...mapState(['count']) } }此时就可以把count当作成为一个计算属性。
Mutation用于变更store的数据。但不能使用异步操作
在vuex对象中定义方法
mutations: {
add(state) {
// 变更状态
state.count++
},
sub(state) {
state.count--
}
},在组件中调用
methods: {
add () {
this.$store.commit('add')
}
}方法也可以传递参数,在mutations方法接受参数时第一个参数总是state,之后可以在调用时传入参数
addN (state, step) {
// 变更状态
state.count += step
},addN (step) {
this.$store.commit('addN', step)
}<button @click="addN(3)">+3</button>Mutation同样可以映射成组件的方法。
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['sub'])
}如果通过异步操作变更数据,必须通过 Action,而不能使用 Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据
actions: {
// actions 不能直接修改state中的数据 必须通过context.commit触发
AsyncAdd (context) {
setTimeout(() => {
context.commit('add')
}, 1000)
}
},AsyncAdd () {
this.$store.dispatch('AsyncAdd')
}actions也可以携带参数,方法与Mutation类似。同样可以使用导入的方式
import { mapActions } from 'vuex'
methods: {
...mapActions(['sub'])
}Getter用于对 Store中的数据进行加工处理形成新的数据
getters: {
showNum: state => {
return '当前最新数量是' + state.count
}
},直接使用
this.$store.getters.名称导入使用
import { mapGetters } from 'vuex' computed: { ...mapGetters(['showNum']) }
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 小康博客!
评论
TwikooDisqusjs










