vue2组件通信方式
文章类型:Vue
发布者:hp
发布时间:2023-02-28
组件间的通讯方式
一:props / $emit
父组件通过props的方式向子组件传递数据,而通过$emit 子组件可以向父组件通信
props: ['articles'] this.$emit('onEmitIndex', index)
二:$children / $parent
通过$parent和$children就可以访问组件的实例,访问组件的所有方法和数据
this.$children[0].messageA = 'this is new value'this.$parent.msg
三:provide/ reject
provide来提供变量, 然后再子组件中通过reject来注入变量
provide: { for: "demo" }, inject: ['for'],
四:ref / refs
ref:如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件实例,可以通过实例直接调用组件的方法或访问数据
<component-a ref="comA"></component-a> const comA = this.$refs.comA; console.log(comA.name); // Vue.js
五:eventBus
eventBus 又称为事件总线,在vue中可以使用它来作为沟通桥梁的概念, 是所有组件共用相同的事件中心,可以向该中心注册发送事件或接收事件, 所以组件都可以通知其他组件
$emit:发送事件
$on:接收事件数据
$off:移除事件监听者
import Vue from 'vue'export const EventBus = new Vue()EventBus.$emit('addition', { num:this.num++ }) EventBus.$on('addition', param => { this.count = this.count + param.num; })EventBus.$off('addition', {})
六:Vuex
1:state=>存储数据
2:getters=>计算数据。用于筛选和多个数据数据相关性计算
3:mutations=>改变数据的函数
4:actions=>用于提交mutation改变状态,异步操作
5:modules=>命名空间,区分各个模块的数据、状态、操作
this.$store.commit('receiveAMsg', { AMsg: this.AMessage })
七:localStorage / sessionStorage
配合JSON.parse() / JSON.stringify()做数据格式转换
window.localStorage.getItem(key)window.localStorage.setItem(key,value)
八:$attrs与 $listeners
inheritAttrs:自动挂载到组件根元素上渲染结果上是否显示
<child-com2 v-bind="$attrs"></child-com2>inheritAttrs: false, props: { age: String }, created() { console.log(this.$attrs); // { "name": "zhang", "gender": "女", "height": "158", "title": "程序员成长指北" } }
总结:
1:父子组件通信:props、$parent / $children、 provide / inject 、ref、 $attrs / $listeners
2:兄弟组件通信:eventBus、vuex
3:跨级或者深层通信: eventBus、Vuex、provide / inject 、$attrs / $listeners