vue组件通信的10种方法

1,556 阅读1分钟

常用方法

1,Props(父子组件之间)

//parent
<Child1 msg='prop传值' @transmit = 'transmit'></Child1>

// child
<button @click="toParent">传值</button>
props: {
    msg: {
      type: String,
      default: ''
    },
  },
  methods: {
    toParent() {
      this.$emit('transmit','传给父亲')
    }
  }

2,Eventbus

// main.js
Vue.prototype.$bus = new Vue()
// child2
    this.$bus.$emit('bus', 'bus传值,组件2传过来的')
// child2
    this.$bus.$on('bus', (msg)=> {
      console.log('msg', msg)
    })

3,Vuex

创建唯一的全局数据管理者store,通过它管理数据并通知组件状态变更

边界情况

4,$parent(父子组件之间,兄弟组件之间通信可以通过共同的祖辈搭桥)

// child2
    this.$parent.$emit('bus', 'bus传值,组件2传过来的')
// child2
    this.$parent.$on('bus', (msg)=> {
      console.log('msg', msg)
    })

5,$children(父子组件之间)

可以直接调用子组件的方法,但是不能保证子元素的顺序(存在异步组件的情况)

this.$children[0].toParent()

6,$root访问根组件

访问根组件,与$parent类似

7,$refs

不光可以作用在组件上也可以作用在普通标签上,和$children类似,但是元素更精准

<Child1 ref="child1" msg='prop传值' @transmit = 'transmit'></Child1>
this.$refs.child1.toParent()

8,Provide/inject(可以跨很多代,但是数据不是响应式的,可以人为的传入做过响应式处理的数组对象等)

provide() {
  return { foo: ‘foo’}
}
Inject: [‘foo’]

非prop特性

9,$attrs

包含了父作用域中除了prop,class,style外的特性绑定,可以通过v-bind=”$attrs”传入,实现爷孙组件通信,父组件透传

<!-- 祖先 -->
<parent msg = "msg from grandpa" @foo = 'onFoo'></parent>
<!-- 父组件 -->
<Child2 v-bind='$attrs' v-on="$listeners"></Child2>
<!-- 子组件 -->
<p>{{$attrs.msg}}</p>

10,$listeners

可以通过v-on=”listeners”,将子组件事件派发给祖先,实现爷孙组件通信,父组件透传

// 子组件
this.$emit('foo')