1、组件之间共享数据的方式:
父-子:v-bind属性绑定
子-父:v-on事件绑定
兄弟组件之间共享数据:EventBus
emit发送数据的组件
2、Vuex是用来管理全局数据。实现组件数据共享。
3、基本使用:
store.js文件:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
}
})
main.js文件挂载:
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
4、Vuex核心概念:
state:提供唯一公共数据源;
取值:this.$store.state.属性名
导入mapState函数,将全局数据映射为计算属性即可。
import { mapState } from 'vuex'
export default {
name: 'vuexDemo',
computed: {
...mapState(['count'])
}
}
<template>
<div>
<h3>当前最新的count值为:{{ count }}</h3>
<button>-</button>
</div>
</template>
mutation用于变更Store中的数据,不可以直接操作store中的数据。
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
add(state) {
state.count++
}
},
actions: {
}
})
btnHandle() {
this.$store.commit('add')
}
mutations传递参数:
addN(state, step) {
state.count += step
}
this.$store.commit('addN', 3)
import { mapState, mapMutations } from 'vuex'
methods: {
...mapMutations(['sub']),
btnHandle1() {
this.sub()
}
}
不要在mutions函数中,执行异步操作。
Action用于处理异步任务。
actions: {
addSync(context) {
// 在actions中不能修改state中的数据
// 必须通过context.commit()触发某个mutation才行
setTimeout(() => {
context.commit('add')
}, 1000);
}
}
btnHandle1() {
this.$store.dispatch('addSync')
}
触发actions异步任务携带参数。
...mapActions(['addSync']),
btnHandle2() {
this.addSync()
}
Getter:
getters: {
showNum(state) {
return '当前最新的数据是[' + state.count + ']'
}
}
this.$store.getters.名称
import {mapGetters } from 'vuex'
...mapGetters(['showNum']),