1.1 组件之间共享数据的方式
父向子传值: v-bind 属性绑定,props 来声明需要从父级接收的数据
子向父传值: v-on 事件绑定
兄弟组件之间共享数据: EventBus
$on 接收数据的那个组件
$emit 发送数据的那个组件
1.2 Vuex 是什么
Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。
1.3 使用Vuex 统一管理状态的好处
- 能够在 vuex 中集中管理共享的数据,易于开发和后期的维护;
- 能够高效的实现组件之间的数据共享,提高开发效率;
- 储存在 vuex 中的数据都是响应式的,能够实时保持数据与页面的同步;
1.4 使用Vuex 的步骤
- 安装 vuex 依赖包
npm install vuex --save - 导入 vuex 包
import Vuex from ‘vuex’
Vue.use(Vuex) - 创建 store 对象
const store = new Vuex.store({
// state 中存放的就是全局共享的数据
state:{ count: 0 }
}) - 将 store 对象挂载到vue实例中
new vue({
el: ‘#app’,
render: h =>h(app),
router,
store
//挂载到这里,所有的组件可以直接从store中获取全局的 数据
})
2.1 State
State提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中进行储存。
const store = new Vuex.store({
// state 中存放的就是全局共享的数据
state:{ count: 0 }
- 组件访问State中的数据第一种方式:
this.$store.state.全局数据名称 - 组件访问State中的数据第2种方式:
// 1.从vue种按需导入 mapState 函数
import { mapState } from ‘vuex’
// 2. 通过刚刚导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的 computed 计算属性:
computed:{
…mapState([‘count’])
}
2.2 Mutation
Mutation用于变更 Store 中的数据
第一:只能通过 mutation 变更 Store数据,不可以直接操作 Store 的数据;
第二:虽然繁琐,但是可以集中监控所有数据的变化
// 定义mutation
mutation :{
add(state){
state.count++
}}
// 触发mutation
methods:{ handle:(){
//触发的第一种方式
this.$store.commit('add')
} }
2.3 Mutation
可以在触发传递参数:
// 定义mutation
mutation :{
addN(state,step){
state.count +=step
}}
// 触发mutation
methods:{ handle:(){
//触发的第一种方式
this.$store.commit(‘addN’, 5)
} }
2.4 Mutation
触发mutation的第二种方式:
第一:从vuex 中按需导入mapMutation 函数
import { mapMutation } from ‘vuex’
第二步:映射为当前组件的方法:
methods:{
…mapMutation([‘add’,‘addN’])
}
3.1 Action
Action用于处理异步任务。
如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,Action中还是要通过触发 Mutation 的方式间接变更数据。
// 定义Action
actions:{
addAsync(context){
setTimeout( ()=>{
context.commit(‘add’)
},1000)
}
}
// 触发Action
methods:{
handle(){
//触发action的第一种方式
this.$store.dispatch(‘addAsync’)
}
}
**action 异步任务时 可以携带参数 **
3.2 Action
触发actions的第二种方式:
// 1.从vuex 导入mapActions 函数
import { mapActions } from ‘vuex’
// 2. 映射为当前组件的 methods 方法:
methods:{
…mapActions ([‘addASync’])
}
3.3 Getter
Getter用于对Store 中的数据进行加工处理形成新的数据。
- Getter可以对Store 中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。
- Store 中数据发生变化,Getter的数据也会跟着变化。
getters:{
showNum:state=>{
return state.count + N
}
}
3.4 Getter
使用 getters 的第一种方式:
this.$store.getters.名称
使用 getters 的第二种方式:
import { mapGetters } from ‘vuex’
computed:{
…mapGetters([‘showNum’])
}