vue通信总结
父对子:v-bind
子对父:v-on
兄弟组件之间:EventBus
$on 接收数据的那个组件
$emit 发送数据的那个组件
Vuex是实现组件全局状态管理的一种机制,可以方便的实现组件数据共享。
使用全局store管理
Vuex 统一状态管理
数据集中管理,易于开发和后期维护
高效实现数据共享,提高开发效率
存储vuex中的数据是响应式的,能够实时保持数据与页面的同步
Vuex基础使用
构建store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
}, //唯一公共数据源,定义全局共享数据
//访问:this.$store.state.count
mutations: {
add(state){
state.count++
}
},//用于变更store数据,使用其的变更行为可被集中监控
actions: {
}
})
引入store.js
...
import store from './store'
...
...
new Vue({
...
store,
...
}).$mount('#app')
state => 数据使用
直接使用
this.$store.state.count
mapState
也可按需导入mapState函数,将全局数据映射为当前组件计算属性
import { mapState } from 'vuex'
computed: {
...mapstate(['count'])
}
mutation => 数据更改
触发
在mutation中定义函数后,触发mutation
methods: {
handle1(){
this.$store.commit('add')
}
}
带参数触发
mutations: {
addN(state,step){
state.count+=step
}
}
methods: {
handle1(){
this.$store.commit('addN',3)
}
}
mapMutations
按需引入mutation并映射为methods
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['add','addN'])
}
注:
mutation中不能写入异步代码,否则vue调试器不能正常工作
action => 处理异步
用于处理异步操作
action通过commit触发mutation的方式间接变更数据
定义action
actions: {
addAsync(context){
setTimeout(()=>{
context.commit('add')
},1000)
}
}
触发action
methods: {
handle(){
this.$store.dispatch('addAsync')
}
}
带参数的action
定义对应的mutation时即定义为带参数的
定义actions时定义带参数的
使用action时传入参数
actions: {
addAsync(context,step){
setTimeout(()=>{
context.commit('add',step)
},1000)
}
}
methods: {
handle(){
this.$store.dispatch('addAsync',5)
}
}
mapActions
import { mapActions } from 'vuex'
methods: {
...mapActions(['addAsync'])
}
getter
getter不会修改数据
类似于computer
自动响应store中的数据变化
定义getter
getters: {
showNum: state => {
return '当前最新的数量是'+state.count
}
}
触发getter
this.$store.getters.showNum
mapGetters
import { mapGetters } from 'vuex'
computed: {
...mapGetterss(['showNum'])
}